JavaScript JSON vs XML
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.
JSON Example
The following JSON describes three employees:
Example
{
"employees": [
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
XML Example
The following XML describes the same employees:
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 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
| JSON | XML |
|---|---|
| Uses objects, arrays and typed values | Uses text elements and text attributes |
| Has built-in types like objects and arrays | Element content is text only |
| Uses a small, fixed syntax | Allows custom element and attribute names |
| Does not support comments | Supports comments |
| Does not support namespaces | Supports namespaces |
| Commonly used for application data | Commonly used for documents and structured data |
| Maps directly into JavaScript values | Must 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
{
"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
<person id="101">
<name>John</name>
<skills>
<skill>HTML</skill>
<skill>CSS</skill>
<skill>JavaScript</skill>
</skills>
</person>
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
// JSON text
const text = '{"name":"John","age":30}';
// Parse the JSON text
const person = JSON.parse(text);
Try it Yourself »
The JSON.stringify() method converts a JavaScript value into JSON text.
Example
// JavaScript Object
const person = {name: "John", age: 30};
// Convert the object to JSON
const text = JSON.stringify(person);
Try it Yourself »
Working with XML in JavaScript
JavaScript can parse XML text with the DOMParser object.
Example
// XML text
const text = "<person><name>John</name></person>";
// 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;
Try it Yourself »
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
{"name":"John","age":30}
XML
<person>
<name>John</name>
<age>30</age>
</person>
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
<message>
Please read the <important>safety instructions</important>
before continuing.
</message>
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
<product id="101" currency="USD">
<name>Laptop</name>
<price>899</price>
</product>
JSON does not distinguish between attributes and other properties.
Equivalent JSON
{
"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
<root
xmlns:h="http://www.w3.org/TR/html4/"
xmlns:f="https://example.com/furniture">
<h:table>...</h:table>
<f:table>...</f:table>
</root>
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
{"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>
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
- Fetch a JSON string
- JSON.Parse() directly into JavaScript values
Using XML
- Fetch an XML document
- Use the XML DOM to loop through the document
- 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