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
Expand|Select|Wrap|Line Numbers
- <?xml version="1.0" encoding="UTF-8"?>
- <root>
- <data>
- <id>1</id>
- <name>PHP </name>
- </data>
- <data>
- <id>2</id>
- <name>Table of Contents</name>
- </data>
- <data>
- <id>7</id>
- <name>Getting Started</name>
- </data>
- <data>
- <id>8</id>
- <name>Introduction</name>
- </data>
- <data>
- <id>9</id>
- <name>What is PHP?</name>
- </data>
- <data>
- <id>10</id>
- <name>What can PHP do?</name>
- </data>
- <data>
- <id>11</id>
- <name>A simple tutorial</name>
- </data>
- <data>
- <id>12</id>
- <name>What do I need?</name>
- </data>
- </root>
Expand|Select|Wrap|Line Numbers
- {
- "data": [
- {
- "id" : "1",
- "name" : "PHP"
- },
- {
- "id" : "2",
- "name" : "Table of Contents"
- },
- {
- "id" : "7",
- "name" : "Getting Started"
- },
- {
- "id" : "8",
- "name" : "Introduction"
- },
- {
- "id" : "9",
- "name" : "What is PHP?"
- },
- {
- "id" : "10",
- "name" : "What can PHP do?"
- },
- {
- "id" : "11",
- "name" : "A simple tutorial"
- },
- {
- "id" : "12",
- "name" : "What do I need?"
- }
- ]
- };
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:
Expand|Select|Wrap|Line Numbers
- data.name[0];
Take note that the indexing is zero-based. So this begins with the data in the data variable; it then moves to the item called name and pulls off the first record ([0]); The result is the string value "PHP".
Here are a few more examples using the same variable.
Expand|Select|Wrap|Line Numbers
- data.name[1]
- // Value is Table of Contentsy"
With this little bit of syntax, you can work with any variety of JSON-formatted data, all without any extra JavaScript toolkits or APIs.
Modifying JSON data
Just as you can access data with the dot and bracket notation shown above, you can easily modify data in the same way:
Expand|Select|Wrap|Line Numbers
- data.name[1] = "PHP is HERE";
That's all you need to do to change data in a variable once you've converted from a string to JavaScript objects.
Test Now -Benchmarking AJAX - JSON vs XML
My test results here