2014-07-14 378 views
0

我使用的是CTA API(http://www.transitchicago.com/developers/bustracker.aspx) ,響應是xml。我想在轉換爲json後,在我的骨幹集合中獲取。響應看起來是這樣的:將xml轉換爲json格式

<?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> 

我想它看起來就像這樣:

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

什麼是做到這一點的最好方法是什麼?

+0

嗯,我假設你正在使用JavaScript,因爲你已經添加的標籤是JavaScript的最簡單的方法要做到這一點是使用谷歌飼料https://developers.google.com/feed/v1/reference,或者你可以參考堆棧溢出問題http://stackoverflow.com/questions/246577/can-i-serve-rss -in-JSON –

回答

0

試試這個功能,它的工作很適合我:

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)); 

對於下面的鏈接瞭解更多信息檢查

http://davidwalsh.name/convert-xml-json