Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JSON vs XML

JSON and XML are both formats for receiving data from a web server.

The JSON and XML examples below both define an “employees” object containing an array of three employee records:

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-descriptive and human-readable.
  • Both JSON and XML are hierarchical, containing nested values.
  • Both can be parsed and utilized by various programming languages.
  • Both can be retrieved using an XMLHttpRequest.

JSON is Unlike XML Because

  • JSON does not require end tags.
  • JSON is more concise.
  • JSON is faster to read and write.
  • JSON supports arrays.

Key Difference:

XML requires an XML parser, while JSON can be parsed with a standard JavaScript function.

Why JSON is Better Than XML

Parsing XML is more complex compared to JSON.

JSON is directly parsed into a ready-to-use JavaScript object.

For AJAX applications, JSON is faster and simpler than XML:

With XML:

  • Retrieve an XML document.
  • Loop through the document using the XML DOM.
  • Extract values and assign them to variables.

With JSON:

  • Retrieve a JSON string.
  • Parse the JSON string using JSON.parse().