JSON, An Alternative to XML in AJAX

I admit it. I like Ajax. Sure it’s a dumb buzzword. But, as you’ll recall, in How To Make an Ajax Chat Room, I said something like, It just turns out XML is slightly more usable for complex stuff and that synchronous requests defeat the point. Though Ajat have many uses. The point I was trying to make is that sometimes sending text back instead of XML is nice. For example, I can send back a 1 if the action was successful. But sometimes that isn’t enough. Sometimes, text and XML are both the wrong tools for the job. That’s where JSON comes in.

The Problem With XML

The problem with XML is that it is a bitch to work with. XML files can get big if the file uses meaningful metadata. To boot, they are a pain in the ass to create when all you really want to do is send some simple data that is too complex for regular text. Then, when it comes time to use the XML in JavaScript, one has to do lots of DOM stuff just to get to the data.

Since I don’t do much PHP work, I don’t have to deal with the creation of the XML files. I do, however, have to access the data from the DOM. I got so irritated by it, that I wrote a function in my Ajax class that will convert simple XML files in to Javascript associative arrays. It turns out I was taking an unneeded step.

The Problem With Text

As I mentioned, sending text back is often useful. Since XMLHttpRequest is smart enough to recognize the content type of the returned code, I often send back errors as text and do something similar to this to display the error: if(!ajax_obj.responseXML){alert(ajax_obj.responseText);}. Sometimes, however, I return 1 to alert success and a string error message to give an error. While I’ve made this standard practice, it can get confusing when different Ajax requests get different styles of messages returned.

Additionally, making things more complex, sometimes sending a single raw value back doesn’t require an XML wrapper. For the sake of speeding up the request, the value is sent as text. This mucks with the paradigm I mentioned before.


XML is nice for documents. It’s a pain to work with as a data exchange format. Text is simpler, but can be inconsistent, often not providing enough useful data. That is where JSON picks up.

JSON, short for JavaScript Object Notation, is exactly what it says it is. It is the syntax used to create objects in JavaScript (and apparently Python, too). If you are curious, it would look like this in Javascript:

my_object = {"item1": "value", "item2": "value"};
document.write(my_object["item1"]); // Outputs "value"

You can nest objects inside objects, too.

Using JSON Instead of XML

Outputting XML from PHP is straight forward. JSON is similarly straight forward. The PHP script simply dumps out text similar to the object literal notation shown above (without the variable assignment). The request will be stored in the .responseText

When an XMLHttpRequest is sent to the server and XML is received, the XML is automagically parsed into a variable as a DOM object. JSON requires an extra step to assign the JSON object to a variable that you can use in your script.

my_object =  eval("("+request_object.responseText+")");

It’s pretty easy. If integrated into a class, the eval could be done on-the-fly.

Freddy — I mean, XML vs JSON

I’m still a JSON newb. I’ve done a pretty good deal of Ajax work, though. I’ve seen some very irritating stuff. For example, when fetching a few hundred records in XML format, the file can get large and cause the browser to freeze while the XML is parsed. Since JSON would be no different from executing Javascript code, it should avoid the crawl.

Unless XML tags are really light weight (which defeats the whole metadata concept of XML), the files can get really big. JSON doesn’t need as much tagging, so file sizes can be smaller.

XML is pretty simple to write. JSON is pretty simple to write. XML must be well-formed. JSON must be syntactically correct. JSON just happens to require less typing than XML.

I’m throwing this bonus in, even though it isn’t specific to Javascript: Not all languages have nice support for XML. PHP 4, for example, will do XML; it is just really hard. There are quite a few JSON interpreters for various languages and JavaScript and Python have it built-in. With XML, one has to learn how to use the XML library. With JSON, all one needs to know is how to work with normal objects in that language. Specifically with Javascript, you don’t need to learn DOM scripting to work with JSON. You just need to know how to use associative arrays.

Real World Testing

I did a simple test. I wrote a PHP file that creates an XML file with 300 values and a JSON file with 300 values. I later modified the loop to 1000 values to see if an article I read was true about Ajax breaking down exponentially. It’s basically true, by the way.

To be fair, I had already written the code, then modified it to run on JSON. For that to work, I had to make the JSON output match what would show after my XML file was turned into an object. The XML file was already optimized to be very small. So, while that might give some size overhead to my JSON (since it had to mimmic nodes), it also gives some parsing overhead to my Ajax (since it was converted to an object before use). What I mean is that the code I used could be more efficient (and I might re-write it eventually).

The Javascript reads the XML or JSON file. It uses the information to populate a select. I uploaded it to a server across the country from where I am and I ran the files. The server gets spikes of heavy use, so the results may be skewed.

At 300 records, I couldn’t really tell a difference between the JSON and the AJAX. Early tests at 1000 records, it was debatable. JSON was at least as fast as XML (usually around 7 seconds from refresh until was complete). Some requests were far faster on JSON (2 seconds instead of 7). Later tests revealed a much larger variation, with XML taking 40 seconds and JSON taking only 15.

The Golden Fleece

I like JSON for what it is. It’s very capable and much lighter than XML, both in terms of parsing and in terms of file size. It is a capable alternative to XML and has quite a few undeniable upsides. I’ll probably do further testing before rewriting all my legacy code, but I will be using JSON in the future.

Tags: , , ,

Comments are closed.