Tool (javascript) to convert a XML string to JSON

23,617

Solution 1

This function has worked pretty well for me:

xmlToJson = function(xml) {
    var obj = {};
    if (xml.nodeType == 1) {                
        if (xml.attributes.length > 0) {
            obj["@attributes"] = {};
            for (var j = 0; j < xml.attributes.length; j++) {
                var attribute = xml.attributes.item(j);
                obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
            }
        }
    } else if (xml.nodeType == 3) { 
        obj = xml.nodeValue;
    }            
    if (xml.hasChildNodes()) {
        for (var i = 0; i < xml.childNodes.length; i++) {
            var item = xml.childNodes.item(i);
            var nodeName = item.nodeName;
            if (typeof (obj[nodeName]) == "undefined") {
                obj[nodeName] = xmlToJson(item);
            } else {
                if (typeof (obj[nodeName].push) == "undefined") {
                    var old = obj[nodeName];
                    obj[nodeName] = [];
                    obj[nodeName].push(old);
                }
                obj[nodeName].push(xmlToJson(item));
            }
        }
    }
    return obj;
}

Implementation:

var jsonText = JSON.stringify(xmlToJson(xmlDoc)); // xmlDoc = xml dom document

Solution 2

Another small library for XML <=> JSON is https://github.com/abdmob/x2js

Solution 3

If you're willing to use jQuery, there is:

http://www.fyneworks.com/jquery/xml-to-json/

$.get("http://jfcoder.com/test.xml.php", function(xml){
    var json = $.xml2json(xml);
    $('pre').html(JSON.stringify(json)); // To show result in the browser
});

Using:

<nums>
 <num>00597</num>
 <num>0059</num>
 <num>5978</num>
 <num>5.978</num>
</nums>

Outputs:

{"num":["00597","0059","5978","5.978"]}

http://jfcoder.com/test.php

Share:
23,617
David Laberge
Author by

David Laberge

Javascript, jQuery, AngularJs, KnockoutJs, PHP, MySQL @nonelinkedin

Updated on July 30, 2022

Comments

  • David Laberge
    David Laberge almost 2 years

    What is the best javascript function/plugin/library to convert a XML string to JSON.

    I found that tool : http://www.thomasfrank.se/xml_to_json.html, but it does not like strings starting with 0. i.e.: 005321 get converted to 2769 (not cool :( )

    My question, what is the best javascript function/plugin/library to convert a XML to JSON?

    EDIT : Someone tried one that works fine?

    • stivlo
      stivlo over 12 years
      why don't you try to write to the author about that?
    • Jared Farrish
      Jared Farrish over 12 years
      @stivlo - There's a big note at the top of the page that says the author wants people to use something else "due to numerous problems reported".
    • Pointy
      Pointy over 12 years
      That script doesn't even generate valid JSON, as it stands.
    • stivlo
      stivlo over 12 years
      oops, right Jared, so David did you try the one suggested?
  • David Laberge
    David Laberge over 12 years
    Great Solution !! Thanks
  • lambshaanxy
    lambshaanxy over 12 years
    This library loses tags embedded in text: <p>Hello <strong>bold</strong> and <em>italic</em></p> becomes {"p":"Helloand"}.
  • lambshaanxy
    lambshaanxy over 12 years
    One handy improvement: if you change typeof (obj[nodeName].length) == "undefined" to typeof (obj[nodeName].push) == "undefined", it stops blowing on whitespace and text elements between tags.
  • Claude
    Claude about 12 years
    I've been using Object.prototype.toString.call( obj[nodeName] ) !== '[object Array]' to avoid the same problem.
  • James Johnson
    James Johnson about 12 years
    @Claude: Just updated my answer with the fix suggested by jpatokal: if (typeof (obj[nodeName].push) == "undefined")
  • Anand Jha
    Anand Jha over 10 years
    @james it returns object({}) in case of single child node could it returns like ([{}]) please?
  • Nikola Radosavljević
    Nikola Radosavljević about 10 years
    It'd be nice to reference source
  • froggythefrog
    froggythefrog over 7 years
    One thing that really lost me on this answer is the "xml" parameter is not just a string. It's supposed to be a Titanium.XML.DOMDocument. Otherwise, how could you possibly call xml.hasChildNodes(), for example? If this was mentioned somewhere, I missed it.
  • Yene Mulatu
    Yene Mulatu almost 7 years
    who has committed plagiarism? davidwalsh.name/convert-xml-json
  • James Johnson
    James Johnson almost 7 years
    @YeneMulatu: Plagiarism? Show me where I claimed to have created this code. I claimed that it worked well for me, and probably because it was used within a project that I contributed on. This site is about helping other developers by sharing code and solutions to solve problems. Dude, get your rep up before you start lobbing BS accusations at people who have established themselves over years as trusted community members and contributors.