Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to pretty print JSON in Grails 1.3.7?

The JSON in question is being read in from a RESTful service, and I would like to print it out (to console, although in .gsp would be fine also) for debugging purposes. Groovy 1.3.7 (current as of August 2011) uses Groovy 1.7.8 (which does not have the JsonOutput introduced in 1.8)

Note I am currently reading it in like this, which I am not convinced is the 'grooviest or grail-est' way to do it - perhaps I could take advantage of the converters and pretty printing if done differently? Code sample would be appreciated.

   def serviceURL = new URL(theURL)
   def json = new JSONObject(serviceURL.text)
   println json
like image 915
Peter Avatar asked Aug 24 '11 21:08

Peter


1 Answers

You can pretty print JSON with the toString(int indentFactor) method. Example:

def json = new JSONObject()
json.put('foo', 'bar')
json.put('blat', 'greep')
println json
===>{"foo":"bar","blat","greep"}
println json.toString(4)
===>{
    "foo": "bar",
    "blat": "greep"
}
like image 137
ataylor Avatar answered Nov 12 '22 06:11

ataylor