How to Convert XML to JSON in JavaScript ?
Last Updated :
18 Apr, 2024
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"
}
Share your thoughts in the comments
Please Login to comment...