Friday, June 11, 2010

Holy crap, JSON is awesome

I'm not an uber web app guy, I put together a monster of a webapp for my last job, and it was all based on XML shuffling between the browser and C# backend. And recently, I picked up a side job building a webapp that catalogs videos.

Here's how I thought "AJAX" worked:

The client JS does a GET with XmlHttpRequest.
The server does some work, like querying a SQL database. It then bundles it all up in XML, maybe via a DOM, or even just pushing strings out the response character stream.
The client receives the XML, (in the XmlDom object that exists inside the XmlHttpRequest), if you get it wrong, the parser is null, and responseText contains the ill formed results.
The client then walks the xml, and does stuff with it. Walking XML is kinda painful in JS, since I never know what value or child or whatever to use to 'get' my data out of.

The weakest link becomes the code I write to convert to and from XML.

Then Trimbo told me to use JSON.

JSON is a string representation of a JS object. a JS object can be created with name value pairs in a 'csv' like format, or it can be made with the normal JS assignment (using 'dot').

The JSON website has a neat little file called JSON2.JS that has "stringify" and "parse" functions that convert back and forth to a JSON string and a JS Object.
So, once I make a regular JS object, for example, the results from a form, I can stringify that, and shove it over the wire with a XmlHttpRequest POST.

So, Instead of nonsense like:
var xmlOut = ""+name+"";
xmlOut += ""+dateOfBirth.toString()+"";
...

I can do:
var outObject;

outObject.name = name;
outObject.dob = dateOfBirth;
...

var outString = JSON.stringify(outObject);

Easier to read, and a lot harder to screw up.

On the server side, I picked up a json library for Java, also on Json.org, and use that to 'put' and 'get' string value pairs from received objects.

This cleaned up by code considerably, and I don't really 'worry' about screwing up XML generation or XML parsing any more.