JS Web APIsLesson #188

JavaScript JSON vs XML

JSON and XML are text formats used to store and exchange structured information.

JSON and XML are text formats used to store and exchange structured information.

JSON is commonly used for data exchange in web applications.

XML is commonly used for documents, configuration files, and established data formats.

Note > JSON and XML solve some of the same problems, but they use different structures. > Neither format is best for every situation.

Share

JSON Example

The following JSON describes three employees:

Example

Example Code

javascript
Try it Yourself
{

  "employees": [

    {"firstName":"John", "lastName":"Doe"},

    {"firstName":"Anna", "lastName":"Smith"},

    {"firstName":"Peter", "lastName":"Jones"}

  ]

}

XML Example

The following XML describes the same employees:

Example

Example Code

html
Try it Yourself
John

     Doe

     Anna

     Smith

     Peter

     Jones

JSON and XML Similarities

JSON and XML have several similarities:

  • Both are text formats.
  • Both can represent structured information.
  • Both can represent nested data.
  • Both can be stored in files.
  • Both can be sent between applications.
  • Both are supported by many programming languages.

JSON and XML Differences

JSONXML
Uses objects, arrays and typed valuesUses text elements and text attributes
Has built-in types like objects and arraysElement content is text only
Uses a small, fixed syntaxAllows custom element and attribute names
Does not support commentsSupports comments
Does not support namespacesSupports namespaces
Commonly used for application dataCommonly used for documents and structured data
Maps directly into JavaScript valuesMust be be converted into JavaScript values
Parsed in JavaScript with JSON.parse()Parsed in JavaScript with DOMParser()

JSON Uses Objects and Arrays

JSON organizes information with objects and arrays.

Example

Example Code

javascript
Try it Yourself
{

  "name": "John",

  "skills": ["HTML", "CSS", "JavaScript"]

}
Note > This structure maps naturally to JavaScript objects and arrays.

XML Uses Elements

XML organizes information with elements and attributes.

Example

Example Code

html
Try it Yourself
John HTML CSS JavaScript
XML contains elements with text, attributes, and other elements. --- ## Working with JSON in JavaScript JavaScript provides built-in methods for working with JSON.

The JSON.parse() method converts JSON text into a JavaScript value.

Example

Example Code

javascript
Try it Yourself
// JSON text

const text = '{"name":"John","age":30}';

// Parse the JSON text

const person = JSON.parse(text);

The JSON.stringify() method converts a JavaScript value into JSON text.

Example

Example Code

javascript
Try it Yourself
// JavaScript Object

const person = {name: "John", age: 30};

// Convert the object to JSON

const text = JSON.stringify(person);

Working with XML in JavaScript

JavaScript can parse XML text with the DOMParser object.

Example

Example Code

javascript
Try it Yourself
// XML text

const text = "

John"; // Parse the XML text const parser = new DOMParser(); const xmlDoc = parser.parseFromString(text, "text/xml"); // Extract name using DOM method const name = xmlDoc.getElementsByTagName("name")[0].textContent;
The parsed XML becomes a document that can be accessed with DOM methods. --- ## JSON Is More Compact JSON often needs fewer characters than XML to represent the same data.

Example

Example Code

javascript
Try it Yourself
{"name":"John","age":30}
File size depends on the structure and content. > JSON is not always smaller than XML. > Compact data can be useful when information is frequently transferred between applications.

XML Can Represent Documents

XML can represent information where text and markup appear together.

Example

Example Code

html
Try it Yourself
Please read the  safety instructions

  before continuing.

This is called mixed content.

Mixed content makes XML suitable for many document formats.

JSON is normally better suited to data structures made from values, objects, and arrays.


XML Attributes

XML can store information in both elements and attributes.

Example

Example Code

html
Try it Yourself
Laptop 899

JSON does not distinguish between attributes and other properties.

Equivalent JSON

Example Code

javascript
Try it Yourself
{

  "id": 101,

  "currency": "USD",

  "name": "Laptop",

  "price": 899

}

XML Namespaces

XML namespaces can distinguish elements that use the same name but have different meanings.

Example

Example Code

html
Try it Yourself
...

   ...
An HTML table is not the same as a furniture table. > JSON does not have a built-in namespace system.

Validation

Both JSON and XML data can be checked against rules.

XML documents can be validated with formats such as DTD and XML Schema.

JSON documents can be validated with JSON Schema.

Validation is useful when applications must agree on the required structure and allowed values.


JSON or XML?

Use the format that matches the data and the systems exchanging it.

JSON is often simpler for data used directly by JavaScript applications.

XML provides features that are useful for documents and more complex markup systems.

Do not choose a format only because it is newer or more popular. > Choose the format that best fits the application.

Server Data

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 3 employees:

JSON Example

Example Code

javascript
Try it Yourself
{"employees":[

  { "firstName":"John", "lastName":"Doe" },

  { "firstName":"Anna", "lastName":"Smith" },

  { "firstName":"Peter", "lastName":"Jones" }

]}
When receiving data from a server, you will have to know the format, and how to use it.

JSON and XML Similarities

  • Both are text formats for structured information.
  • Both are self describing (human readable)
  • Both are hierarchical (values within values)
  • Both are language independent
  • Both can be parsed by a parser
  • Both can be fetched from a server

Is JSON is Better than XML

Neither format is best for every situation.

For Fetch operations, JSON is faster and easier than XML:

Using JSON

1. Fetch a JSON string 2. JSON.Parse() directly into JavaScript values

Using XML

1. Fetch an XML document 2. Use the XML DOM to loop through the document 3. Extract values and store in variables

JSON maps directly into JavaScript object. > XML is more difficult to parse.

When to Use JSON

JSON is a good choice for:

  • Web APIs
  • Sending application data
  • Configuration files
  • Data stored by JavaScript applications
  • Data structures based on objects and arrays

When to Use XML

XML is a good choice for:

  • Content containing both text and markup
  • Systems based on XML schemas and namespaces
  • Existing applications that already use XML
  • Established XML-based storage systems

Interactive Code Examples

JS Example 1

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
{

  "employees": [

    {"firstName":"John", "lastName":"Doe"},

    {"firstName":"Anna", "lastName":"Smith"},

    {"firstName":"Peter", "lastName":"Jones"}

  ]

}

JS Example 2

html
Try it Yourself
JavaScript syntax and algorithm demonstration.
<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>

JS Example 3

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
{

  "name": "John",

  "skills": ["HTML", "CSS", "JavaScript"]

}

JS Example 4

html
Try it Yourself
JavaScript syntax and algorithm demonstration.
<person id="101">

  <name>John</name>

  <skills>

    <skill>HTML</skill>

    <skill>CSS</skill>

    <skill>JavaScript</skill>

  </skills>

</person>

JS Example 5

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
// JSON text

const text = '{"name":"John","age":30}';



// Parse the JSON text

const person = JSON.parse(text);

JS Example 6

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
// JavaScript Object

const person = {name: "John", age: 30};



// Convert the object to JSON

const text = JSON.stringify(person);