Home > programming > Getting groovy with JSON

Getting groovy with JSON

September 17th, 2006 Leave a comment Go to comments

JSON is an informal standard for describing structured data. It is human-readable, less verbose than XML, and has a distinct advantage which I’ll mention later.

Short example: say you want to define an address book entry. In JSON it might look like this:

1
2
3
4
5
 { 'name': 'John Doe',
   'address': '42, Universe Rd.',
   'telephone': [{'home': '1-901-555-2323'},
                 {'cell': '1-888-555-9999'} ]
 }

Compare the verbosity of the above to the equivalent XML here:

1
2
3
4
5
6
7
8
<person>
  <name>John Doe</name>
  <address>42, Universe Rd.</address>
  <telephones>
    <telephone type="home" number="1-901-555-2323" />
    <telephone type="cell" number="1-888-555-9999" />
  </telephones>
</person>

Using JSON, you can nest arbitrarily structured data, making use of maps (comma-separated lists of forms like ‘key’: ‘value’, surrounded by braces) and sequences (comma-separated values, surrounded by brackets).

You can use JSON in lots of places, even in those where the more “enterprisey” developers would use XML; like, say, to write config files.

However there is a particular affinity between JSON and the AJAX techniques. While doing AJAX you’ll often find the need to fetch some data from the server and parse it. Guess what: in JavaScript you don’t need a parser to parse JSON, because JSON syntax is JavaScript syntax. In other words, you parse it by calling eval().
JSON after all stands for ‘JavaScript Object Notation’ :)

And, as you probably guessed, generating JSON is a breeze. Here’s a quick’n'dirty function written in the Groovy programming language, that serializes a construct of Java maps and lists into JSON:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def toJSON( obj ) {
    if( ! obj ) return "";
    if( obj instanceof Map ) {
        return "{" + obj.keySet().inject("") { accu, k |
            (accu.length() == 0? "": "${accu},\\n") +
            "'${k}': ${toJSON(obj[k])}"
        } + "\\n}"
    }
    if( obj instanceof List || obj instanceof Set ) {
        return "[" + obj.inject("") { accu, item |
            (accu.length() == 0? "": "${accu},\\n") +
            toJSON(item)
        } + "]"
    }
    return "'${obj}'"
}
Categories: programming
  1. July 6th, 2007 at 07:02 | #1

    There is another usefull JSON serializer/unserializer library
    http://jroller.com/page/aalmiray/?anchor=json_lib_features_for_2

  2. yu_li_yan
    July 8th, 2007 at 17:08 | #2

    Cool! Thanks for sharing.

  3. June 11th, 2008 at 01:19 | #3

    Thanks for this. BTW, using “copy to clipboard” caused “funky quotes” to be copied over on the last line of code.

    Cheers!

  4. June 11th, 2008 at 01:52 | #4

    Hmm, you might want to add a few unit tests for this outputter. Currently, the numeric value 0 isn’t handled correctly. Also, single quotes are not escaped correctly.

  5. yu_li_yan
    June 19th, 2008 at 17:03 | #5

    Haw-Bin, thanks for your comment; yes indeed the example is just a dirty hack, only meant to demonstrate JSON.

  6. September 9th, 2009 at 15:41 | #6

    The fix the 0 handling issue, just change

    if( ! obj ) return “”;

    to

    if( obj == null ) return “”;

  1. No trackbacks yet.