JSON vs XML
Both JSON and XML are used to receive data from web servers.
JSON and XML differ in their syntax, as shown below:
JSON Example
{
"sites": [
{ "name":"tutorialpro.org" , "url":"www.tutorialpro.org" },
{ "name":"google" , "url":"www.google.com" },
{ "name":"微博" , "url":"www.weibo.com" }
]
}
XML Example
<sites>
<site>
<name>tutorialpro.org</name> <url>www.tutorialpro.org</url>
</site>
<site>
<name>google</name> <url>www.google.com</url>
</site>
<site>
<name>微博</name> <url>www.weibo.com</url>
</site>
</sites>
Similarities between JSON and XML:
- JSON and XML data are "self-descriptive" and easy to understand.
- JSON and XML data have hierarchical structures.
- JSON and XML data can be used by most programming languages.
- JSON does not require end tags.
- JSON is more concise.
- JSON has faster read and write speeds.
- JSON can use arrays.
The biggest difference is: XML requires an XML parser to parse, while JSON can be parsed using standard JavaScript functions.
- JSON.parse(): Converts a JSON string to a JavaScript object.
- JSON.stringify(): Converts a JavaScript value to a JSON string.
Why is JSON Better Than XML?
XML is harder to parse than JSON.
JSON can directly use existing JavaScript objects for parsing.
For AJAX applications, JSON loads data faster and is simpler:
Using XML:
- Retrieve the XML document.
- Iterate through the document using XML DOM.
- Parse and assign the data to variables.
Using JSON:
- Retrieve the JSON string.
- Parse the JSON string using JSON.parse.
Related Articles
- JavaScript JSON: https://www.tutorialpro.org/js/js-json.html
- XML DOM Tutorial: https://www.tutorialpro.org/dom/dom-tutorial.html