JSON vs XML
Both JSON and XML can be used to receive data from a web server.
The following JSON and XML examples both define an employees object, with an array of 3 employees:
3 | { "firstName": "John", "lastName": "Doe" }, |
4 | { "firstName": "Anna", "lastName": "Smith" }, |
5 | { "firstName": "Peter", "lastName": "Jones" } |
|
2 | < employee > < firstName >John</ firstName > < lastName >Doe</ lastName > </ employee > |
3 | < employee > < firstName >Anna</ firstName > < lastName >Smith</ lastName > </ employee > |
4 | < employee > < firstName >Peter</ firstName > < lastName >Jones</ lastName > </ employee > |
|
JSON is like XML because
- Both are “self describing” (human readable).
- Both are hierarchical (values within values).
- Both can be parsed and used by lots of programming languages.
- Both can be fetched with an XMLHttpRequest.
JSON is unlike XML because
- JSON does not use end tag.
- JSON is shorter.
- JSON is quicker to read and write.
- JSON can use arrays.
The biggest difference is
XML has to be parsed with an XML parser, and JSON can be parsed by a standard JavaScript function.
Why JSON Is Better Than XML
It is because
- XML is much more difficult to parse than JSON.
- JSON is parsed into a ready-to-use JavaScript object.
For AJAX applications, JSON is faster and easier than XML because the following steps are taken if XML is used:
- Fetch an XML document,
- Use the XML DOM to loop through the document, and
- Extract values and store in variables.
and if JSON is used:
- Fetch a JSON string and
JSON.parse
the JSON string.
Demonstration
The following demonstration shows how the script of HTML and JavaScript is displayed on the Web.
Why is abbreviation such a long word?
― Steve Wright
|