-2
我得到了一些將對象嵌套在對象中的json。我需要提取名稱爲「body」的每個實體。有沒有辦法做到這一點,而不寫一個長的算法?如何從JSON數組中獲取具有某個名稱的所有實體
http://www.reddit.com/r/AskReddit/comments/22rx5c.json
我得到了一些將對象嵌套在對象中的json。我需要提取名稱爲「body」的每個實體。有沒有辦法做到這一點,而不寫一個長的算法?如何從JSON數組中獲取具有某個名稱的所有實體
http://www.reddit.com/r/AskReddit/comments/22rx5c.json
你需要通過每個節點及其子節點遞歸循環,並檢查他們的鍵名。有這樣的圖書館可以幫助你。或者,您可以使用xpath for JSON。
你可以試試這樣:
$.getJSON('http://www.reddit.com/r/AskReddit/comments/22rx5c.json', function(json){
result = [];
recurse('body', json);
console.log(result);
});
function recurse(toFind, json){
for(var key in json){
if(typeof json[key] == 'object'){
recurse(toFind, json[key]);
}
if(key == toFind){
result[result.length] = json[key];
}
}
};
在這裏你可以找到JSFiddle
請你加入,你已經嘗試過的問題的代碼。 – Andy