0

I am using the CTA API (http://www.transitchicago.com/developers/bustracker.aspx) and the responses are xml. I'd like to convert to json after my fetch in a backbone collection. The response looks like this:

<?xml version="1.0"?>
<bustime-response>
<route>
    <rt>1</rt>
    <rtnm>Bronzeville/Union Station</rtnm>
    <rtclr>#336633</rtclr>
</route>        
<route>
    <rt>2</rt>
    <rtnm>Hyde Park Express</rtnm>
    <rtclr>#993366</rtclr>
</route>        
</bustime-response>

I'd like it to look like this:

[
  {
    "rt": "1",
    "rtnm": "Bronzeville/Union Station",
    "rtclr": "#336633"
  },
  {
    "rt": "2",
    "rtnm": "Hyde Park Express",
    "rtclr": "#993366"
  }
]

What's the best way to do this?

1

1 Answer 1

0

Try this function,it worked 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;
 }

 var jsonText = JSON.stringify(xmlToJson(xmlDoc)); 

For more information check below Link

http://davidwalsh.name/convert-xml-json
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.