6

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?

4
  • why don't you try to write to the author about that? Commented Oct 14, 2011 at 15:25
  • @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". Commented Oct 14, 2011 at 15:26
  • That script doesn't even generate valid JSON, as it stands. Commented Oct 14, 2011 at 15:30
  • 2
    oops, right Jared, so David did you try the one suggested? Commented Oct 14, 2011 at 15:31

3 Answers 3

18

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
Sign up to request clarification or add additional context in comments.

8 Comments

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.
I've been using Object.prototype.toString.call( obj[nodeName] ) !== '[object Array]' to avoid the same problem.
@Claude: Just updated my answer with the fix suggested by jpatokal: if (typeof (obj[nodeName].push) == "undefined")
@james it returns object({}) in case of single child node could it returns like ([{}]) please?
It'd be nice to reference source
|
6

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

Comments

2

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

1 Comment

This library loses tags embedded in text: <p>Hello <strong>bold</strong> and <em>italic</em></p> becomes {"p":"Helloand"}.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.