Possible to pretty print JSON in Grails 1.3.7?
Asked Answered
T

4

8

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
Tenstrike answered 24/8, 2011 at 21:32 Comment(0)
K
14

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"
}
Kew answered 24/8, 2011 at 21:41 Comment(0)
S
5

You can use grails.converters.JSON (which is the most commonly used library for JSON):

In your config.groovy file, add the line to set prettyPrint to true:

grails.converters.default.pretty.print=true

Then, in your controller:

import grails.converters.*

def serviceURL = new URL(theURL)
def json = JSON.parse(serviceURL.text)
println "JSON RESPONSE: ${json.toString()"
Stodge answered 1/11, 2011 at 22:26 Comment(0)
U
4

If you're in a Grails controller and plan to render the json, then you use something like this (using Grails 2.3.5):

public prettyJson() {
    JSON json = ['status': 'OK'] as JSON
    json.prettyPrint = true
    json.render response
}

I found that solution here: http://www.intelligrape.com/blog/2012/07/16/rendering-json-with-formatting/

Uttica answered 24/2, 2014 at 14:21 Comment(0)
A
1

Apart from set default pretty print in Config.groovy, JSON's toString() method accepts one boolean parameter. It controls whether pretty print the result or not.

import grails.converters.*
import my.data.*

def accountJson = Account.get(1001) as JSON
println(accountJson.toString(true))
println(accountJson.toString(false))

Tested in Grails 1.3.9.

Aksum answered 15/6, 2017 at 3:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.