当响应不在数组中时,在javascript中解析JSON结果

时间:2014-02-17 14:56:45

标签: javascript json

在进行Javascript API调用时,我得到的结果如下:

{
"data": {
    "2 Broke Girls": {
        "air_by_date": 0, 
        "cache": {
            "banner": 1, 
            "poster": 1
        }, 
        "language": "en", 
        "network": "CBS", 
        "next_ep_airdate": "2014-02-24", 
        "paused": 0, 
        "quality": "HD", 
        "show_name": "2 Broke Girls", 
        "status": "Continuing", 
        "tvdbid": 248741, 
        "tvrage_id": 28416, 
        "tvrage_name": "2 Broke Girls"
    }, 
    "Alias": {
        ...
    },
    "message": "", 
    "result": "success"
    }
}

如何成功迭代所有正在返回的不同节目?我不能使用response.data.SHOWNAME因为节目会在很多地方改变。

我使用$.each()尝试了几个解决方案,但我并没有真正得到这些解决方案。 我可以自己访问每个节目标题,但其他数据仍然被返回为[Object object]

编辑:为了使它更清晰,我需要访问该字段。     response.data.RANDOM_TITLE.tvrage_name& response.data.RANDOM_TITLE.status

5 个答案:

答案 0 :(得分:2)

我也是!

function getShows (json) {

    // grab just the data part
    var data = JSON.parse(json).data,
        i,

        // empty array for your shows
        shows = [];

    // delete the crap you don't want
    delete data.message;
    delete data.result;

    // loop through everything else
    for (i in data) {

        // make sure it's an own property
        if (data.hasOwnProperty(i)) {

            // add to you collection of shows
            shows.push(data[i]);
        }
    }

    // tada
    return shows;
}

答案 1 :(得分:0)

您可以访问以下数据:

for(var show_name in response.data) {
    var show = response.data[show_name];
    if(!(show instanceof Object)) continue;
    console.log(show_name, show); 
    //note that not all browsers will print the "show" object, 
    //IE will just say [object]
}

答案 2 :(得分:0)

for (name in data) {
   if (data.hasOwnProperty(name)){
      //code here
      //make sure to ignore message and result and any other special results returned. 
      showDetails = data[name];
   }
}

这里的数据是返回的响应。

答案 3 :(得分:0)

您可以将返回的数据分配到变量中。

eg

var jsonData = data;
for(var i=0;t<=jsonData.length;i++){
    console.log(jsonData[i].data);
}

答案 4 :(得分:0)

您可以这样访问:

var dkeys = Object.keys(d.data);
for (var i=0; i < dkeys.length; i++) {
    if (typeof d.data[dkeys[i]].show_name !== 'undefined') {
        alert(d.data[dkeys[i]].show_name);
    }
}