Archive

Archive for September, 2006

Getting groovy with JSON

September 17th, 2006 6 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