JSON vs XML
- Previous Page JSON Syntax
- Next Page JSON Data Types
JSON and XML can both be used to receive data from web servers.
The following JSON and XML instances define an employee object, containing an array of 3 employees:
JSON instance
{"employees":[ {"firstName":"Bill", "lastName":"Gates" }, {"firstName":"Steve", "lastName":"Jobs" }, {"firstName":"Elon", "lastName":"Musk" } ]}
XML instance
<employees> <employee> <firstName>Bill</firstName> <lastName>Gates</lastName> </employee> <employee> <firstName>Steve</firstName> <lastName>Jobs</lastName> </employee> <employee> <firstName>Elon</firstName> <lastName>Musk</lastName> </employee> </employees>
JSON is similar to XML because:
- Both JSON and XML are 'self-descriptive' (human-readable)
- Both JSON and XML are hierarchical (values contain values)
- Both JSON and XML can be parsed and used by a large number of programming languages
- Both JSON and XML can be read by XMLHttpRequest
The differences between JSON and XML are:
- JSON does not use tags
- JSON is shorter
- JSON has faster read and write speeds
- JSON can use arrays
The biggest difference is:
XML must be parsed using an XML parser. While JSON can be parsed through standard JavaScript functions.
Why is JSON better than XML?
- XML is more difficult to parse than JSON.
- JSON is parsed into a JavaScript object that can be used.
For AJAX applications, JSON is faster and easier to use than XML:
Use XML
- Read XML Document
- Use XML DOM to traverse the document
- Extract the value stored in the variable
Use JSON
- Read JSON String
- JSON.Parse JSON String
- Previous Page JSON Syntax
- Next Page JSON Data Types