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.class.name}"
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.

10 comments:

  1. 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

    ReplyDelete
  2. 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 ;-)

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

    ReplyDelete
  4. 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.

    ReplyDelete
  5. Hello,
    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?
    Thanks!

    ReplyDelete
  6. @babe
    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 prettyjson.com.

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

    http://www.cerny-online.com/cerny.js/demos/json-pretty-printing

    ReplyDelete
  8. Here is an idea plugin that does JSON formatting.
    http://dontmindthelanguage.wordpress.com/2009/02/05/intellij-json-formatter-plugin/

    ReplyDelete
  9. Thanks for good post.

    I have question related JSON render.

    How will render JSON in gsp files

    ReplyDelete
  10. I love this blog post Plz RT

    ReplyDelete