Imdadullah Babu
Full Stack Developer
2024-02-17
Full Stack Developer
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.
Before the conversion process, let's discuss why you might want to convert XML to JSON:
There are multiple ways to convert XML to JSON in JavaScript, but one common approach involves using built-in browser APIs or third-party libraries. We'll explore both methods.
1var xmlString = `
2<bookstore>
3 <book category="fiction">
4 <title>The Great Gatsby</title>
5 <author>F. Scott Fitzgerald</author>
6 <year>1925</year>
7 </book>
8 <book category="fiction">
9 <title>To Kill a Mockingbird</title>
10 <author>Harper Lee</author>
11 <year>1960</year>
12 </book>
13</bookstore>`;
14
15// Parse XML string
16var parser = new DOMParser();
17var xmlDoc = parser.parseFromString(xmlString, "text/xml");
18
19// Convert XML to JSON
20function xmlToJson(xml) {
21 var obj = {};
22
23 if (xml.nodeType == 1) { // Element
24 if (xml.attributes.length > 0) {
25 obj["@attributes"] = {};
26 for (var j = 0; j < xml.attributes.length; j++) {
27 var attribute = xml.attributes.item(j);
28 obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
29 }
30 }
31 } else if (xml.nodeType == 3) { // Text
32 obj = xml.nodeValue.trim();
33 }
34
35 if (xml.hasChildNodes()) {
36 for (var i = 0; i < xml.childNodes.length; i++) {
37 var item = xml.childNodes.item(i);
38 var nodeName = item.nodeName;
39 if (typeof(obj[nodeName]) == "undefined") {
40 obj[nodeName] = xmlToJson(item);
41 } else {
42 if (typeof(obj[nodeName].push) == "undefined") {
43 var old = obj[nodeName];
44 obj[nodeName] = [];
45 obj[nodeName].push(old);
46 }
47 obj[nodeName].push(xmlToJson(item));
48 }
49 }
50 }
51 return obj;
52}
53
54var jsonData = xmlToJson(xmlDoc);
55console.log(JSON.stringify(jsonData, null, 2));
You can also utilize third-party libraries like xml-js for more straightforward XML to JSON conversion:
1const convert = require('xml-js');
2
3// Convert XML to JSON
4const json = convert.xml2json(xmlString, {compact: true, spaces: 2});
5console.log(json);
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 to use built-in browser APIs or third-party libraries, understanding the process empowers you to work effectively with different data formats in your projects.
© 2024 IMDOS | All right reserved