Convert XML to JSON String in JavaScript



Some popular formats for data exchange are XML (eXtensible Markup Language) and JSON (JavaScript Object Notation). Tags are used to structure XML, while JSON is a more condensed key-value format. In JavaScript apps, this is common. Converting XML data to JSON could occasionally be required in order to facilitate or alter data in JavaScript.

Several techniques for converting XML to JSON using JavaScript are examined in this article. from developing unique JavaScript frameworks and solutions to employing DOM analysis.

Understanding XML and JSON

XML Example

<person>
    <name>Pankaj</name>
    <age>20</age>
    <city>Surat</city>
</person>

JSON Equivalent

{
  "person": {
    "name": "Pankaj",
    "age": "20",
    "city": "Surat"
  }
}

The XML data has a hierarchical structure, while the JSON version uses nested objects. Converting between these formats involves parsing XML tags and attributes to create key-value pairs.

Approaches to Convert XML to JSON String

Using DOMParser and Recursion

DOMParser API parses XML strings into DOM objects making it easier to traverse and convert them into JSON.

Example Code

function xmlToJson(xml) {
  const obj = {};
  if (xml.nodeType === 1) { // Element node
    if (xml.attributes.length > 0) {
      obj["@attributes"] = {};
      for (let i = 0; i < xml.attributes.length; i++) {
        const attribute = xml.attributes[i];
        obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
      }
    }
  } else if (xml.nodeType === 3) { // Text node
    obj = xml.nodeValue;
  }

  if (xml.hasChildNodes()) {
    for (let i = 0; i < xml.childNodes.length; i++) {
      const item = xml.childNodes.item(i);
      const nodeName = item.nodeName;
      if (typeof(obj[nodeName]) === "undefined") {
        obj[nodeName] = xmlToJson(item);
      } else {
        if (typeof(obj[nodeName].push) === "undefined") {
          obj[nodeName] = [obj[nodeName]];
        }
        obj[nodeName].push(xmlToJson(item));
      }
    }
  }
  return obj;
}

const xmlString = `<person><name>Pankaj</name><age>20</age><city>Surat</city>`;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "application/xml");
console.log(JSON.stringify(xmlToJson(xmlDoc.documentElement)));

Output

{
  "person": {
    "name": "Pankaj",
    "age": "20",
    "city": "Surat"
  }
}

Using xml2json Library

Using a library like xml2json can make conversion easier. Especially for complex XML structures you can include this library via CDN or install it in your Node.js project.

Example Code

// Assuming xml2json library is available
const xmlString = `<person><name>Pankaj</name><age>20</age><city>Surat</city>`;
const json = xml2json(xmlString, {compact: true, spaces: 2});
console.log(json);

Output

{
  "person": {
    "name": "Pankaj",
    "age": "20",
    "city": "Surat"
  }
}

Using Custom JavaScript Logic

If you only need to handle simple XML structure a custom parser might be better and here we will manually parse XML tags and attributes.

Example Code

function customXmlToJson(xml) {
  const obj = {};
  const regex = /<([^/]+?)>([^<]+)<\/\1>/g;
  let match;
  while ((match = regex.exec(xml))) {
    obj[match[1]] = match[2];
  }
  return obj;
}

const xmlString = `<person><name>Pankaj</name><age>20</age><city>Surat</city></person>`;
console.log(JSON.stringify(customXmlToJson(xmlString)));

Output

{
  "person": {
    "name": "Pankaj",
    "age": "20",
    "city": "Surat"
  }
}

Handling Edge Cases

  • Attributes in XML: If the XML has attributes (e.g., <name gender="male">Pankaj</name>), they should be stored separately in JSON under an @attributes key to avoid collisions with tag content.
  • Empty Tags: Tags with no content (e.g., <city />) should map to null in JSON.
  • Arrays in XML: Repeated tags in XML (e.g., multiple <phone> entries) should convert to arrays in JSON to preserve data structure.
Updated on: 2024-11-06T09:55:31+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements