JSON vs. XML: What Should You Use?

Lots of people have asked me this question: which is better when loading data via an ajax request? JSON is my favorite. I’m going to try and explain the benefits of JSON over XML.

From the start, JSON is already has a leg up on XML for one reason: it’s faster. To read XML you need to parse it, read the nodes, attributes, and child nodes in the XML document, and then use the data that you’ve found.

In jQuery the easiest way to do that is to use the built-in ajax functions to call the XML and use the each function to loop through all the nodes. The each function is nice, but is much much slower than a for loop. Just imagine what happens when we have an XML document with multiple levels of nested nodes you need to get at. You end up with multiple nested $.each functions and without much trying, you end up with a script that crawls. With JSON it’s easy to get at the data since its already native javascript. No parsers or proxies necessary–all you need to do is loop through the data, fast and simple. That’s one point for JSON.

There are aspects of XML that people point to as reasons to use it. First, XML is both human and machine readable. It is nice to see what data is being returned just by viewing the source, but that problem is solved by having good documentation, including an example of the JSON that will be returned. Also, being a front-end developer, I spend a lot of my time reading javascript anyway. I find it just as easy to read as XML, it’s just different.

Another good reason to use XML is that it’s widely available. Lots of websites offer APIs to get at their public (and sometimes private) data, and I usually find the returned format of these APIs are often either XML or JSON. However since XML has been around longer than JSON, there is simply more XML out there.

Sometimes you might find yourself in a situation where you don’t have JSON as an option. So do you submit to the API gods and slow down your site and just use the XML? Why do that when you can write the API yourself! This is where some server side skills come in handy. It’s super easy to load an XML document via PHP and print out the data in whatever format you need it to be in.

So in conclusion, you should be using JSON every chance you get.

2 thoughts on “JSON vs. XML: What Should You Use?”

  1. could you be so kind to provide some performance tests between JSON and XML ? you say XML is slower… is it possible to see some figures? :) good stuff, thanks.

Comments are closed.