Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert XML to JSON (and back) using Javascript

People also ask

Can we convert XML to JSON in JavaScript?

log(json); }); That above example code parses an XML string and converts it into a JavaScript object. To convert the JavaScript object into its JSON representation, we are using the JSON. stringify() method.

How can you convert XML to JSON?

To convert an XML document to JSON, follow these steps: Select the XML to JSON action from the Tools > JSON Tools menu. Choose or enter the Input URL of the XML document. Choose the path of the Output file that will contain the resulting JSON document.


I think this is the best one: Converting between XML and JSON

Be sure to read the accompanying article on the xml.com O'Reilly site, which goes into details of the problems with these conversions, which I think you will find enlightening. The fact that O'Reilly is hosting the article should indicate that Stefan's solution has merit.


https://github.com/abdmob/x2js - my own library (updated URL from http://code.google.com/p/x2js/):

This library provides XML to JSON (JavaScript Objects) and vice versa javascript conversion functions. The library is very small and doesn't require any other additional libraries.

API functions

  • new X2JS() - to create your instance to access all library functionality. Also you could specify optional configuration options here
  • X2JS.xml2json - Convert XML specified as DOM Object to JSON
  • X2JS.json2xml - Convert JSON to XML DOM Object
  • X2JS.xml_str2json - Convert XML specified as string to JSON
  • X2JS.json2xml_str - Convert JSON to XML string

Online Demo on http://jsfiddle.net/abdmob/gkxucxrj/1/

var x2js = new X2JS();
function convertXml2JSon() {
    $("#jsonArea").val(JSON.stringify(x2js.xml_str2json($("#xmlArea").val())));
}

function convertJSon2XML() {
    $("#xmlArea").val(x2js.json2xml_str($.parseJSON($("#jsonArea").val())));
}

convertXml2JSon();
convertJSon2XML();
$("#convertToJsonBtn").click(convertXml2JSon);
$("#convertToXmlBtn").click(convertJSon2XML);

These answers helped me a lot to make this function:

function xml2json(xml) {
  try {
    var obj = {};
    if (xml.children.length > 0) {
      for (var i = 0; i < xml.children.length; i++) {
        var item = xml.children.item(i);
        var nodeName = item.nodeName;

        if (typeof (obj[nodeName]) == "undefined") {
          obj[nodeName] = xml2json(item);
        } else {
          if (typeof (obj[nodeName].push) == "undefined") {
            var old = obj[nodeName];

            obj[nodeName] = [];
            obj[nodeName].push(old);
          }
          obj[nodeName].push(xml2json(item));
        }
      }
    } else {
      obj = xml.textContent;
    }
    return obj;
  } catch (e) {
      console.log(e.message);
  }
}

As long as you pass in a jquery dom/xml object: for me it was:

Jquery(this).find('content').eq(0)[0]

where content was the field I was storing my xml in.


A while back I wrote this tool https://bitbucket.org/surenrao/xml2json for my TV Watchlist app, hope this helps too.

Synopsys: A library to not only convert xml to json, but is also easy to debug (without circular errors) and recreate json back to xml. Features :- Parse xml to json object. Print json object back to xml. Can be used to save xml in IndexedDB as X2J objects. Print json object.


I've created a recursive function based on regex, in case you don't want to install library and understand the logic behind what's happening:

const xmlSample = '<tag>tag content</tag><tag2>another content</tag2><tag3><insideTag>inside content</insideTag><emptyTag /></tag3>';
console.log(parseXmlToJson(xmlSample));

function parseXmlToJson(xml) {
    const json = {};
    for (const res of xml.matchAll(/(?:<(\w*)(?:\s[^>]*)*>)((?:(?!<\1).)*)(?:<\/\1>)|<(\w*)(?:\s*)*\/>/gm)) {
        const key = res[1] || res[3];
        const value = res[2] && parseXmlToJson(res[2]);
        json[key] = ((value && Object.keys(value).length) ? value : res[2]) || null;

    }
    return json;
}

Regex explanation for each loop:

  • res[0] - return the xml (as is)
  • res[1] - return the xml tag name
  • res[2] - return the xml content
  • res[3] - return the xml tag name in case the tag closes itself. In example: <tag />

You can check how the regex works here: https://regex101.com/r/ZJpCAL/1

Note: In case json has a key with an undefined value, it is being removed. That's why I've inserted null at the end of line 9.