Convert XML to JSON in JavaScript

Convert XML to JSON in JavaScript

  1. The Extensible Markup Language (XML)
  2. The JavaScript Object Notation (JSON)
  3. Use the matchAll() Method to Convert XML to JSON in JavaScript

In this article, we will learn how to convert XML strings to JSON format data with the help of regex and the default string method matchAll() in JavaScript.

The Extensible Markup Language (XML)

The Extensible Markup Language (XML) is a markup language close to HTML. It doesn’t have pre-defined tags like HTML, but we can define our tags for our requirements.

We can store, search, and share the data using XML.

Example:

<root>
<tag>tag content</tag>
<tag2>another content</tag2>
</root>

We need to open and close the tag with / like HTML.

The JavaScript Object Notation (JSON)

JavaScript Object Notation (JSON) is a text format to store and transport data. It is self-describing and easy to understand.

In JSON, we store data in key-value pairs (each key has a value).

Example:

'{"name":"Bravo", "age":40, "car":null}'

Use the matchAll() Method to Convert XML to JSON in JavaScript

There are multiple ways to convert or translate XML data into JSON accurately. We will learn to convert XML to JSON using regex (regular expression) and the default JavaScript string method matchAll().

The JavaScript method matchAll() returns an iterator of all results by matching a string with the help of the provided regex.

User-provided input (XML):

<root><tag>tag content</tag><tag2>another content</tag2></root>

Expected JSON output after conversion:

[object Object] {
    root: [object Object] {
        tag: "tag content",
        tag2: "another content"
    }
}

In the example below, we will use an XML string and implement the matchALL() method with regex to convert it into the JSON data format.

Regex required:

regex = /(?:<(\w*)(?:\s[^>]*)*>)((?:(?!<\1).)*)(?:<\/\1>)|<(\w*)(?:\s*)*\/>/gm;

Example:

<script>
const xmlString = '<root><tag>tag content</tag><tag2>another content</tag2></root>'; //provided xml

function convertXmlToJson(xmlString) {
    const jsonData = {};
    for (const result of xmlString.matchAll(/(?:<(\w*)(?:\s[^>]*)*>)((?:(?!<\1).)*)(?:<\/\1>)|<(\w*)(?:\s*)*\/>/gm)) {
        const key = result[1] || result[3];
        const value = result[2] && convertXmlToJson(result[2]); //recusrion
        jsonData[key] = ((value && Object.keys(value).length) ? value : result[2]) || null;
    }
    return jsonData;
}
console.log("Data after converting to JSON:")
console.log(convertXmlToJson(xmlString)); //print the result in logs
</script>

Output:

"Data after converting to JSON:"
[object Object] {
    root: [object Object] {
        tag: "tag content",
        tag2: "another content"
    }
}

Explanation:

  • In the example, we initialized the XML string to a variable to generate JSON data.

  • We have declared a function convertXmlToJson() to get the XML string as argument.

  • In that function, we used the for loop to iterate the execution on the XML string with matchAll(regex).

  • Inside the body of the loop, we are creating keys and values and storing the result in the already declared variable const jsonData = {}.

  • You can see a function called convertXmlToJson() inside the body itself. It is known as recursion (recursive function).

    Recursive functions are called in their braces to iterate the execution.

  • Then, we simply return the convertXmlToJson() with the jsonData variable.

  • We use the console.log() method to call the function and display the returned result.

Related Article - JavaScript JSON

  • Generate Formatted and Easy-To-Read JSON in JavaScript
  • Convert CSV to JSON in JavaScript
  • POST a JSON Object Using Fetch API in JavaScript
  • Convert JSON to XML in JavaScript
  • Check if a String Is a Valid JSON String in JavaScript