JSON – better than XML?

Probably.

JavaScript coders have been doing it for ages. Now it’s got a name: JSON, or JavaScript Object Notation.

One of the sexier features of JavaScript is a shorthand notations for defining and populating a data structure containing objects and arrays. So, instead of:

me = new Object() ;
me.name = 'Nick' ;
me.age = 30 ;
me.hobby = new Array()
me.hobby[0] = 'Reading' ;
me.hobby[1] = 'Writing' ;
me.smelly = false ;

You can do this…

me = {
    name : 'Nick' ,
    age : 30 ,
    hobby : ['Reading', 'TV'] ,
    smelly : false
} ;

Try doing that in PHP. This is almost the equivalent of the XML:

<me>
    <name>Nick</name>
    <age>30</age>
    <hobby>Reading</hobby>
    <hobby>TV</hobby>
    <smelly>false</smelly>
</me>

Ideally, when you get XML data from a server, you’d have a standard function to automatically parse the XML and convert it into a data structure just like one in JavaScript above.

But there’s a problem here: a standard function like this doesn’t know whether to expect just one, or more than one, tag of each type to appear. Which means it doesn’t know whether to represent an item as a scalar type (string, boolean, integer, etc), or as an array. Looking at the XML code itself doesn’t help, because even if there’s only one hobby (for example) in there, we’d still like it to come back as an array.

Moreover, we don’t know which of the scalar types apply to each of the tags. In the case of name, and maybe age, this isn’t a problem. But with smelly, this is: if we assume its value the string “false”, instead of the boolean FALSE, JavaScript will treat the value of smelly as true in a boolean context – and that’s an error.

The only solution with XML is to write a custom wrapper for each XML schema to convert it into a correct data structure.

What a waste of time. Twice over: once for parsing the XML, and again for writing loads of wrappers.

Why not skip the XML, and just send the raw JavaScript notation? It’s much more transparent to other languages, containing more ‘hinting’ information about the types uses in the structure; it’s fairly easily parsed; and, of course, the total size of the data sent or stored is considerably smaller.

Head over to http://www.json.org for some JSON specs, compilers and parsers.

Latest News & Insights

Say connected – get Loft updates straight to your inbox.