2013-08-21 114 views
1

由於其他用戶在我的其他thread建議的問候在這裏發表另一個問題來解釋如何訪問JSON對象。我使用的代碼是:訪問字符串化JSON對象

<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script> 
<script> 
$(function() { 
    $.getJSON(
     "https://api.guildwars2.com/v1/wvw/matches.json", 
     function (data) { 
      $("#reply").html(JSON.stringify(data)); 
      // or work with the data here, already in object format 
     }); 
}); 
</script> 

我試圖用the JSON code做的,就是通過一個指定world_id搜索和返回match_id。我對JavaScript非常陌生,所以我不太清楚如何去做,以及如何訪問上面代碼給出的字符串化數據。

我想出如何做到這一點的方法是,創建一個數組,並通過每個對象存儲在裏面,然後循環並檢查是否有匹配的ID一樣,

if(obj[i].red_world_id == 'xxxx' || obj[i].blue_world_id == 'xxxx' || obj[i].green_world_id == 'xxxx') { 
    return obj[i].wvw_match_id; 
} 

我唯一的問題是我不知道如何將數組設置爲JSON數據。關於jQuery.grep信息

function(data) { 
    var filteredArray=$.grep(data.wvw_matches, function (item) { 
     return (item.red_world_id == 'xxxx' || item.blue_world_id == 'xxxx' || item.green_world_id == 'xxxx'); 
    }); 
} 

See this page: -

+0

您應該追加JSON。 – crush

+0

這個json已經是一個數組了 –

+5

在把它變成一個字符串之前,你已經擁有了一個對象,並且你可以直接迭代並搜索那些鍵和值,那麼爲什麼把它變成一個字符串呢? – adeneo

回答

2

。使用此代碼

$(function() { 
    $.getJSON("https://api.guildwars2.com/v1/wvw/matches.json", function(
      data) { 
     $("#reply").html(JSON.stringify(data)); 
     // or work with the data here, already in object format 
     var result = [];//for if it has many matches 
     for (var i=0;i<data.wvw_matches.length;i++) { 
      var obj = data.wvw_matches[i]; 
      if (obj.red_world_id == 'xxxx' || obj.blue_world_id == 'xxxx' 
        || obj.green_world_id == 'xxxx') { 
       result.push(obj.wvw_match_id); 
      } 
     } 
    }); 
}); 
+3

您不應該使用'for ... in'來遍歷數組。此外,它應該是'data.wvw_matches'而不是'data'。您應該使用'for(var i = 0; i crush

+3

從異步請求中返回一個值將不會做任何事情。 – dc5

+1

對不起,只是一個複製粘貼錯誤 –

1

沒有必要字符串化,你可以直接將JSON對象工作。