2024-02-17

Convert XML to JSON with JavaScript

Explore how to convert XML to JSON using JavaScript, providing an in-depth guide along with code snippets to help you understand the process and implement it in your projects.

Imdad

Imdadullah Babu

Full Stack Developer

[object Object]

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 the conversion process, let's discuss why you might want to convert XML to JSON:

  1. JavaScript Friendliness: JSON is native to JavaScript, making it easy to work with in web applications built with JavaScript.
  2. Simplicity and Readability: JSON tends to be more concise and human-readable compared to XML, which can be verbose.
  3. Compatibility: Many modern APIs and libraries prefer JSON for data exchange, so converting XML to JSON can facilitate integration with such systems.

Converting XML to JSON with JavaScript

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.

Using Browser APIs:

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));

Using Third-Party Libraries (xml-js):

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);

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 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.

Share with your friends

IMDOS.IN

© 2024 IMDOS | All right reserved