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:
JSON Example
{ "employees": [ { "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ]}
XML Example
<employees> <employee> <firstName>John</firstName> <lastName>Doe</lastName> </employee> <employee> <firstName>Anna</firstName> <lastName>Smith</lastName> </employee> <employee> <firstName>Peter</firstName> <lastName>Jones</lastName> </employee></employees>
JSON is Like XML Because
- Both JSON and XML are "self-describing" (human-readable).
- Both JSON and XML are hierarchical (values within values).
- Both JSON and XML can be parsed and used by many programming languages.
- Both JSON and XML can be fetched with an XMLHttpRequest.
JSON is Unlike XML Because
- JSON doesn't use end tags.
- 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, whereas JSON can be parsed by a standard JavaScript function.
Why JSON is Better Than XML
- 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:
Using XML:
- Fetch an XML document.
- Use the XML DOM to loop through the document.
- Extract values and store them in variables.
Using JSON:
- Fetch a JSON string.
- Parse the JSON string into a JavaScript object using JSON.parse().
- Access the data directly from the JavaScript object.
Example:
Fetching and Parsing JSON:
let jsonString = '{"employees":[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"},{"firstName":"Peter","lastName":"Jones"}]}';let obj = JSON.parse(jsonString);let firstName = obj.employees[0].firstName; // John
Fetching and Parsing XML:
let xmlString = '<employees><employee><firstName>John</firstName><lastName>Doe</lastName></employee><employee><firstName>Anna</firstName><lastName>Smith</lastName></employee><employee><firstName>Peter</firstName><lastName>Jones</lastName></employee></employees>';let parser = new DOMParser();let xmlDoc = parser.parseFromString(xmlString, "text/xml");let firstName = xmlDoc.getElementsByTagName("firstName")[0].childNodes[0].nodeValue; // John