All in the <head> – Ponderings and code by Drew McLellan –

JSON All The Way

I’m increasingly coming around to the realisation that JSON is pretty much the best way to consume external data within JavaScript. If you’re providing a web service or API that’s returning data in XML format, you really need to start offering a JSON output option if you want to encourage use of your service. It’s becoming essential.

Parsing XML in JavaScript is awkward and unpleasant. There are chunky inconsistancies between implementations in different browsers, and whilst you can abstract this away with a library (anyone know a good one for XML?) you can save yourself untold amounts of hassle using JSON as it is inherently native to the language.

Brief aside: if you’re not familiar, JavaScript Object Notation is a method of describing data structures such as arrays and objects and their contents in plain text. On receiving a chunk of JSON you can eval() it to recreate the data structure within your script – the objects become live objects and the arrays become arrays that can be read and written, and so on. You can read more about JSON.

This morning I spent around about an hour working with an API which, as far as I could see, only returned XML. Previously, I’d done quite a bit of work with Ajax and XML and so am pretty familiar with handling it, at least on a manual XHR level. In this situation, however, I was needing to use the YUI libraries for the first time. For one reason or another, the response back form the server was an XML document as plain text, which I then needed to load into a DOM document. I’m not sure if it was that the YUI Ajax stuff doesn’t support DOM documents in some way, or whether it because the response was text/plain rather than text/xml, but either way I was needing to create a document and load it up form a string. Turns out this is one of those things that’s not only different across browsers’ XML implementations, but in some cases isn’t even complete.

After working myself into a frustrated mess involving DOM documents that looked like they were loaded but in truth were only sort of a bit loaded, I turned back to the API documentation to double check that there wasn’t a JSON option. The docs had nothing, so I had a go and querystring hacking until I found that yes, indeed, it did support JSON, it was just that some nincompoop had neglected to document it. I ripped out my browser-specific XML hacks and eval()ed the JSON instead, and I was up and running with data in the page in literally a matter of minutes.

JSON is simple, effective and robust. It’s worth saying again:- if you want people to hack on your APIs, roll out JSON support.