In the world of web development and data interchange, converting between different data formats is a common task. XML (eXtensible Markup Language) and JSON (JavaScript Object Notation) are two popular formats used for structuring and transmitting data over the internet. While XML has been around for longer and has widespread adoption, JSON has gained popularity due to its simplicity and ease of use, especially with JavaScript.
Why Convert XML to JSON?
Before diving into the conversion process, let's discuss why you might want to convert XML to JSON:
- JavaScript Friendliness — JSON is native to JavaScript, making it easy to work with in web applications built with JavaScript.
- Simplicity and Readability — JSON tends to be more concise and human-readable compared to verbose XML.
- Compatibility — Many modern APIs and libraries prefer JSON, so converting XML facilitates easier integration with such systems.
Converting XML to JSON with JavaScript
There are multiple ways to convert XML to JSON in JavaScript — using built-in browser APIs or third-party libraries. We'll explore both methods.
Method 01 — Using Browser APIs
var xmlString = `
<bookstore>
<book category="fiction">
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<year>1925</year>
</book>
<book category="fiction">
<title>To Kill a Mockingbird</title>
<author>Harper Lee</author>
<year>1960</year>
</book>
</bookstore>`;
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlString, "text/xml");
function xmlToJson(xml) {
var obj = {};
if (xml.nodeType == 1) {
if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType == 3) {
obj = xml.nodeValue.trim();
}
if (xml.hasChildNodes()) {
for (var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if (typeof(obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if (typeof(obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
}
var jsonData = xmlToJson(xmlDoc);
console.log(JSON.stringify(jsonData, null, 2));Method 02 — Using xml-js Library
You can also utilize third-party libraries like xml-js for more straightforward XML to JSON conversion:
const convert = require('xml-js');
// Convert XML to JSON
const json = convert.xml2json(xmlString, { compact: true, spaces: 2 });
console.log(json);Conclusion
Converting XML to JSON with JavaScript is a valuable skill for web developers, enabling seamless data interchange and integration with modern systems and APIs. Whether you choose built-in browser APIs or third-party libraries, understanding the process empowers you to work effectively with different data formats in your projects.






