开发者

Tool (javascript) to convert a XML string to JSON [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, argum开发者_JAVA技巧ents, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 10 years ago.

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?


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜