AJAX - JSON vs. XML
JSON vs. XML
JSON and XML are basically used for the same purpose—to represent
and interchange data. I'll try to show you why you might want to use
JSON rather than XML in an AJAX context by showing you an example of
how an data class (actually, a list of PHP documentation pages) might be
represented, first in XML. and then in JSON. This side-by-side
comparison should let you begin to understand how to represent data in
JSON. The XML version:
XML Version | JSON Version |
---|---|
<?xml version="1.0" encoding="UTF-8"?> |
|
There's nothing complicated going on here; now data
contains the JSON formatted data we've been looking at throughout this
article. However, this doesn't do much, as the data still isn't in a
format that is obviously useful.
JSON Responses + Accessing the data While it might not be obvious, that lengthy string above is just an array, and once you've got that array in a JavaScript variable, you can access it easily. In fact, you can simply separate the array with period delimiters. So, to access the name of the first entry of the PHP documentation pages, you would use code like this in your JavaScript:
Take note that the indexing is zero-based. So this begins with the data in the Here are a few more examples using the same variable.
With this little bit of syntax, you can work with any variety of JSON-formatted data, all without any extra JavaScript toolkits or APIs. Just as you can access data with the dot and bracket notation shown above, you can easily modify data in the same way:
That's all you need to do to change data in a variable once you've converted from a string to JavaScript objects. |
XML Responses + Accessing the data The following code shows the source code used in retrieving the XML document. The getPage() function takes the URL from where you will retrieve the XML document. The function does so by setting up a reference to the XMLHTTP Request object, which does the task of retrieving and parsing the XML document as described in the XMLDOM. This is done after checking the status and availability of the document on the server. var root = xhr.responseXML;
11
To access individual elements below
This is a lot of work to extract a single value from an XML document, especially when that document has a simple structure. It's easy to see how this method to extract data from XML can quickly become unwieldy. If I combine all the steps above into a single DOM reference, it looks like this:
|
Benchmarking( JSON vs XML )
FIREFOX 3
First Scenario (Retrive 1000 rows and 2 columns from Database Table)
test.js -> 55.35 Kb Vs test.xml-> 127.39 KBSecond Scenario (Retrive 1000 rows and 4 columns from Database Table)
test4.js => 124.21 KB Vs test4.xml ->249.27 KBFirst Scenario -AJAX JSON | First Scenario -AJAX XML |
jsonT.data.length= 1000 jsonT.data[999].name= RESPONSE FROM SERVER Total time JSON in = 47 ms |
XML.length= 1000 XML.data[999].name= RESPONSE FROM SERVER Total time XML in = 198 ms |
Second Scenario -AJAX JSON | Second Scenario -AJAX XML |
json.data.length= 1000 json.data[900].name= RESPONSE FROM SERVER() Total time JSON in = 68 ms |
XML.length= 1000 XML.data[900].name=RESPONSE FROM SERVER() Total time XML in =768 ms |
Internet Explorer
First Scenario (Retrive 1000 rows and 2 columns from Database Table)
test.js -> 55.35 Kb Vs test.xml-> 127.39 KBSecond Scenario (Retrive 1000 rows and 4 columns from Database Table)
test4.js => 124.21 KB Vs test4.xml ->249.27 KBFirst Scenario -AJAX JSON | First Scenario -AJAX XML |
jsonT.data.length= 1000 jsonT.data[900].name= RESPONSE FROM SERVER Total time JSON in = 43 ms |
XML.length= 1000 XML.data[900].name= RESPONSE FROM SERVER Total time XML in = 196 ms |
Second Scenario -AJAX JSON | Second Scenario -AJAX XML |
json.data.length= 1000 json.data[900].name= RESPONSE FROM SERVER() Total time JSON in = 77 ms |
XML.length= 1000 XML.data[900].name=RESPONSE FROM SERVER() Total time XML in =770 ms |
SAFARI
First Scenario (Retrive 1000 rows and 2 columns from Database Table)
test.js -> 55.35 Kb Vs test.xml-> 127.39 KBSecond Scenario (Retrive 1000 rows and 4 columns from Database Table)
test4.js => 124.21 KB Vs test4.xml ->249.27 KBFirst Scenario -AJAX JSON | First Scenario -AJAX XML |
jsonT.data.length= 1000 jsonT.data[900].name= RESPONSE FROM SERVER Total time JSON in = 48 ms |
XML.length= 1000 XML.data[900].name= RESPONSE FROM SERVER Total time XML in = 207 ms |
Second Scenario -AJAX JSON | Second Scenario -AJAX XML |
json.data.length= 1000 json.data[900].name= RESPONSE FROM SERVER() Total time JSON in = 69 ms |
XML.length= 1000 XML.data[900].name=RESPONSE FROM SERVER() Total time XML in =827 ms |
CHROME
First Scenario (Retrive 1000 rows and 2 columns from Database Table)
test.js -> 55.35 Kb Vs test.xml-> 127.39 KBSecond Scenario (Retrive 1000 rows and 4 columns from Database Table)
test4.js => 124.21 KB Vs test4.xml ->249.27 KBFirst Scenario -AJAX JSON | First Scenario -AJAX XML |
jsonT.data.length= 1000 jsonT.data[900].name= RESPONSE FROM SERVER Total time JSON in = 49 ms |
XML.length= 1000 XML.data[900].name= RESPONSE FROM SERVER Total time XML in = 211 ms |
Second Scenario -AJAX JSON | Second Scenario -AJAX XML |
json.data.length= 1000 json.data[900].name= RESPONSE FROM SERVER() Total time JSON in = 72 ms |
XML.length= 1000 XML.data[900].name=RESPONSE FROM SERVER() Total time XML in =810 ms |
JSON is a winner!!!!!
Test in your browser -Benchmarking AJAX - JSON vs XML.
The end result is that when you're already working with lots of JavaScript objects, JSON is almost certainly a good bet for you to easily convert your data into a format that is simple to send in your requests to server-side programs.
Is JSON Fast and Reliable?
JSON produces smaller documents, and JSON is certainly easier to use in JavaScript. XMLHttpRequest parses XML documents for you whereas you have to manually parse JSON, but is parsing JSON slower than parsing XML? I tested the XML parser built into XMLHttpRequest against JSON on these data and put them through thousands of iterations. Parsing JSON was 2 -10 times faster than parsing XML! .When it comes to making AJAX behave like a desktop application, speed is everything, and clearly, JSON is a winner See our Tests results-Benchmarking AJAX - JSON vs XML.
Key Characteristic Differences between XML and JSONCharacteristic | XML | JSON |
---|---|---|
Data types | Does not provide any notion of data types. One must rely on XML Schema for adding type information. | Provides scalar data types and the ability to express structured data through arrays and objects. |
Support for arrays | Arrays have to be expressed by conventions, for example through the use of an outer placeholder element that models the arrays contents as inner elements. Typically, the outer element uses the plural form of the name used for inner elements. | Native array support. |
Support for objects | Objects have to be expressed by conventions, often through a mixed use of attributes and elements. | Native object support. |
Null support | Requires use of xsi:nil on elements in an XML instance document plus an import of the corresponding namespace. | Natively recognizes the null value. |
Comments | Native support and usually available through APIs. | Not supported. |
Namespaces | Supports namespaces, which eliminates the risk of name collisions when combining documents. Namespaces also allow existing XML-based standards to be safely extended. | No concept of namespaces. Naming collisions are usually avoided by nesting objects or using a prefix in an object member name (the former is preferred in practice). |
Formatting decisions | Complex. Requires a greater effort to decide how to map application types to XML elements and attributes. Can create heated debates whether an element-centric or attribute-centric approach is better. | Simple. Provides a much more direct mapping for application data. The only exception may be the absence of date/time literal. |
Size | Documents tend to be lengthy in size, especially when an element-centric approach to formatting is used. | Syntax is very terse and yields formatted text where most of the space is consumed (rightly so) by the represented data. |
Parsing in JavaScript | Requires an XML DOM implementation and additional application code to map text back into JavaScript objects. | No additional application code required to parse text; can use JavaScript's eval function. |
Learning curve | Generally tends to require use of several technologies in concert: XPath, XML Schema, XSLT, XML Namespaces, the DOM, and so on. | Very simple technology stack that is already familiar to developers with a background in JavaScript or other dynamic programming languages. |
Of course, you might not always have control of the server-side that's producing data for your AJAX application. You might be using a third-party server for your data and it's possible that server provides only XML output. And, if it happens to provide JSON, are you sure you really want to use it?
Notice in your example that you passed the response text directly into a call to eval. If you trust and control the server, that's probably okay. If not, a malicious server could have your browsers executing dangerous actions. In that case, you're better off using a JSON parser written in JavaScript. Luckily, one already exists.
You can evaluate JSON directly in Python, or take advantage of a safe JSON parser instead. Parsers for JSON exist in dozens of other languages as well; the JSON.org Web site lists them.
You can refer to the org.json
package documentation for more details. (Note: If you want more detail go on the org.json )
Conclusion
The future is JSON ?
Right now JSON is in its infancy, however it's a pretty big baby. PHP supports JSON in version 5. And the first cracks in XML's domination of RSS are just starting to appear.
In 2008 most browsers will be able to parse JSON and to convert any variable into JSON. There is also an upcoming standard (also from Douglas Crockford) which will enable a browser to securely request a JSONfile from outside the current domain. When both of these technologies have been implemented, we will be entering the world of Web 3.0 where any browser can request any JSON published data anywhere in the world and manipulate it to its own ends without the need to involve any proxy servers.
XML when it was introduced made waves, but JSON, when it is fully supported by the browser, will make tsunamis and if you're not already preparing for that day, and the new applications browser-supported JSON will enable then you're very much cheating yourself out of a front-row seat at the next revolution.
JSON's clever idea of being a subset of JavaScript (and Python) makes it an instantly useable, lightweight, and highly nimble way to handle data interchange for AJAX. It's faster to parse and vastly easier to use than XML. It's bound to become the buzzword of the day for "Web 2.0." Any developer, whether of the standard desktop application variety or of Web applications, is bound to appreciate its simplicity and adroitness. I hope you enjoy using JSON in your own buzzword-compliant, Web-2.0-based, AJAX-enabled, agile, rapid application development, on-or-off-rails applications.