JSON vs XML
JSON and XML are both used to receive data from web servers.
JSON and XML differ in syntax, as shown below:
JSON Example
{
"sites": [
{ "name":"Example" , "url":"www.example.com" },
{ "name":"google" , "url":"www.google.com" },
{ "name":"Weibo" , "url":"www.weibo.com" }
]
}
XML Example
<sites>
<site>
<name>Example</name> <url>www.example.com</url>
</site>
<site>
<name>google</name> <url>www.google.com</url>
</site>
<site>
<name>Weibo</name> <url>www.weibo.com</url>
</site>
</sites>
Similarities between JSON and XML:
- Both JSON and XML data are "self-describing" and easy to understand.
- Both JSON and XML data are hierarchical structures.
- Both JSON and XML data can be used by most programming languages.
- JSON does not require end tags.
- JSON is more concise.
- JSON reads and writes faster.
- 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(): Convert a JSON string into a JavaScript object.
- JSON.stringify(): Convert a JavaScript value into a JSON string.
Why is JSON better than XML?
XML is harder to parse than JSON.
JSON can be parsed directly using existing JavaScript objects.
For AJAX applications, JSON loads faster and is simpler than XML:
Using XML
- Get XML document
- Iterate through the document using XML DOM
- Parse the data and assign it to variables
Using JSON
- Get JSON string
- Use JSON.Parse to parse the JSON string
Related Articles
- JavaScript JSON: https://www.example.com/js/js-json.html
- XML DOM Tutorial:https://www.example.com/dom/dom-tutorial.html