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?

Anthony
  • 2,330
  • 8
  • 44
  • 64
  • Well I assume that you are using javascript since you have added tag as javascript easiest way to do this is using Google Feed https://developers.google.com/feed/v1/reference, alternatively you may refer to Stack overflow Question http://stackoverflow.com/questions/246577/can-i-serve-rss-in-json – yash ahuja Jul 14 '14 at 04:51

1 Answers1

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
Unknownman
  • 473
  • 3
  • 9