Friday, July 18, 2008

Grails JSON Parser

Here is a quick example on parsing JSON in grails using groovy (surprisingly, google isn't returning any good hits). Also, if you needed this ability in just straight groovy, I am sure you could include the specific grails jar in your classpath.

import grails.converters.*

def jsonArray = JSON.parse("""['foo','bar', { a: 'JSONObject' }]""")
println "Class of jsonArray: ${}"
jsonArray.each { println "Value: ${it}" }

FYI, it appears from the mailing list this was added around 1.0 RC1.

Building JSON is super easy too in grails/groovy using the render as. And don't forget to import grails.converters.
render Book.list(params) as JSON

Update: Read my recent article on testing REST Services that return JSON using groovy and httpbuilder.


Unknown said...

I enjoy reading your blog entries. I posted some info on using the Grails JSON builder here with Dojo, for those who are interested: Grails & JSON

Andres Almiray said...

I believe producing JSON in Grails has received more electronic ink than consuming it, thanks for the info James.

By the way, you can also use Json-lib for this same purpose ;-)

Anonymous said...

been looking for this all over the place man...thanks

Anonymous said...

Mmmmn. Yummy.

Since the domain objects get rendered as an array don't really need Json-lib - but, I'm sure there's more candy there.

Thanks James. Funny how the development world is so small.

mad-scientist said...

Good post...when i google 'grails json parser', the first page is almost exclusively links to your article!
I'm trying to parse nested json output, and make them display in a user-friendly format, instead of rows and rows of output that looks like garbage...any thoughts on that?

jlorenzen said...

Thanks for the comments. Suggestion for your pretty json would be to buy a mac and then buy textmate. I personally don't have a work mac (yet), several coworkers do and you can format json with one click in textmate. Super easy and super slick.

If you do write a program, make it a public site where anyone can paste in json and your website will spit it out in readable form. Call the site

jlorenzen said...

Here is a pretty print json website where developers can paste their json to view it in a readable fashion.

jlorenzen said...

Here is an idea plugin that does JSON formatting.

nagaraja said...

Thanks for good post.

I have question related JSON render.

How will render JSON in gsp files

Anonymous said...

I love this blog post Plz RT