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.