The Wayback Machine - https://web.archive.org/web/20240621200902/https://www.geeksforgeeks.org/how-to-convert-xml-to-json-in-javascript/
Open In App

How to Convert XML to JSON in JavaScript ?

Last Updated : 18 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Converting XML to JSON in JavaScript is crucial for simplifying data manipulation and compatibility across various systems. Here, we’ll learn two methods to achieve this conversion efficiently.

Below are the approaches to convert XML to JSON in JavaScript:

Using xml-js Library

In this approach, we are using the xml-js library to convert XML to JSON in JavaScript. The xml2json function from the library takes XML data as input and converts it into a JSON object, with options like compact formatting and spacing specified.

Run the below command to install xml-js Library:

npm install xml-js

Example: The below example uses xml-js Library to convert XML to JSON in JavaScript.

JavaScript
const convert = require('xml-js');
const xmlData = `
<data>
    <organization>GeeksforGeeks</organization>
    <founder>Sandeep Jain</founder>
    <location>Noida</location>
</data>
`;
const jsonResult = convert.xml2json(xmlData, {
    compact: true,
    spaces: 2
});
console.log(jsonResult);

Output:

{
"data": {
"organization": {
"_text": "GeeksforGeeks"
},
"founder": {
"_text": "Sandeep Jain"
},
"location": {
"_text": "Noida"
}
}
}

Using DOM Parser

In this approach, we are using the xmldom library’s DOMParser to parse XML data in JavaScript. We traverse the parsed XML document’s nodes to extract element names and their corresponding text content, storing them in a JSON object for conversion and formatting.

Run the below command to install xmldom Library:

npm install xmldom

Example: The below example uses DOM Parser to convert XML to JSON in JavaScript.

JavaScript
const {
    DOMParser
} = require('xmldom');
const xmlString = `
  <data>
      <organization>GeeksforGeeks</organization>
      <founder>Sandeep Jain</founder>
      <location>Noida</location>
  </data>
  `;
const parser = new DOMParser();
const xmlDoc = 
        parser.parseFromString(xmlString, 'text/xml');
const data = {};
const nodes = xmlDoc.documentElement.childNodes;
for (let i = 0; i < nodes.length; i++) {
    const node = nodes[i];
    if (node.nodeType === 1) {
        data[node.nodeName] = node.textContent.trim();
    }
}
const jsonResult = JSON.stringify(data, null, 2);
console.log(jsonResult);

Output:

{
"organization": "GeeksforGeeks",
"founder": "Sandeep Jain",
"location": "Noida"
}

Similar Reads

Convert XML to JSON using JavaScript
Convert XML to JSON effortlessly using JavaScript, enabling seamless integration and manipulation of XML data within your applications. JavaScript libraries like xml-js and xmldom Library simplify the conversion process, ensuring compatibility and efficiency. Below are the approaches to convert XML to JSON in JavaScript: Table of Content Using xml-
2 min read
How to Convert XML data into JSON using PHP ?
In this article, we are going to see how to convert XML data into JSON format using PHP. Requirements: XAMPP Server Introduction: PHP stands for hypertext preprocessor, which is used to create dynamic web pages. It also parses the XML and JSON data. XML stands for an extensible markup language in which we can define our own data. Structure of XML:
3 min read
Convert xml data into json using Node.js
XML: Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. The design goals of XML focus on simplicity, generality, and usability across the Internet. It is a textual data format with strong support via Unicode for different human langua
2 min read
Convert JSON String to Array of JSON Objects in JavaScript
Given a JSON string, the task is to convert it into an array of JSON objects in JavaScript. This array will contain the values derived from the JSON string using JavaScript. There are two approaches to solve this problem, which are discussed below: Approach 1: Using JSON.parse() MethodThe basic method to convert JSON String to Array of JSON object
2 min read
Difference between JSON and XML
JSON (JavaScript Object Notation) is a lightweight data-interchange format and it completely language independent. It is based on the JavaScript programming language and easy to understand and generate. Example : C/C++ Code {&quot;Geeks&quot;:[ { &quot;firstName&quot;:&quot;Vivek&quot;, &quot;lastName&quot;:&quot;Kothari&quot; }, { &quot;firstName
2 min read
JSON to XML Converter
JSON to XML Converter is a tool that converts the JSON file data to the XML file. #content-iframe {width: 100%; height: 720px;} @media (max-width: 768px) {.article--viewer .a-wrapper .content .text #content-iframe {max-width: 100%; min-height: 720px; height: auto;}} @media (max-width: 576px) {.article--viewer .a-wrapper .content .text #content-ifra
2 min read
XML to JSON Converter
Are you dealing with XML data and need to convert it to JSON format? Look no further! Our XML to JSON Converter is your go-to tool for seamless data transformation. Whether you’re a developer, data analyst, or system integrator, this free online converter streamlines the process and ensures compatibility. #content-iframe {width: 100%; height: 720px
2 min read
How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete
2 min read
What is difference between JSON.parse() and JSON.stringify() Methods in JavaScript ?
JSON.parse() converts JSON strings to JavaScript objects, while JSON.stringify() converts JavaScript objects to JSON strings. JavaScript utilizes JSON for data interchange between servers and web pages. These methods enable easy data manipulation and transport in web development. JSON.parse() MethodJSON.parse() converts a JSON string to a JavaScrip
2 min read
JSON Modify an Array Value of a JSON Object
The arrays in JSON (JavaScript Object Notation) are similar to arrays in JavaScript. Arrays in JSON can have values of the following types: nullbooleannumberstringarrayobject The arrays in JavaScript can have all these but it can also have other valid JavaScript expressions which are not allowed in JSON. The array value of a JSON object can be modi
2 min read