[英]How to navigate in nested JSON
我嵌套了 JSON 對象,例如
{"baseball":
{"mlb":
{"regular":
{"_events": [{"start_time": "2011-07-31 17:35", "lines":
[{"comment": "", "coeff": "2.35", "title": "2", "old_coeff": "2.35", "is_main": true},
{"comment": "", "coeff": "1.59", "title": "2", "old_coeff": "1.59", "is_main": true},
{"comment": "", "coeff": "1.59", "title": "2", "old_coeff": "1.59", "is_main": true},
{"comment": "", "coeff": "2.35", "title": "2", "old_coeff": "2.35", "is_main": true}],
"members": ["atlanta", "florida"]
}
]
}}}}
我需要獲取 _events 數組並解析它。 但我不知道在 _events 之前單元格中會有什么以及它們如何。 我如何使用這種結構?
假設您在名為 input 的字符串中有上述內容(並且 JSON 有效):
var obj = JSON.parse(input) // converts it to a JS native object.
// you can descend into the new object this way:
var obj.baseball.mlb.regular._events
作為警告,早期版本的 IE 沒有 JSON.parse,因此您需要為此使用框架。
// find the _events key
var tmp = input.substr(input.indexOf("_events"))
// grab the maximum array contents.
tmp = tmp.substring( tmp.indexOf( "[" ), tmp.indexOf( "]" ) + 1 );
// now we have to search the array
var len = tmp.length;
var count = 0;
for( var i = 0; i < len; i++ )
{
var chr = tmp.charAt(i)
// every time an array opens, increment
if( chr == '[' ) count++;
// every time one closes decrement
else if( chr == ']' ) count--;
// if all arrays are closed, you have a complete set
if( count == 0 ) break;
}
var events = JSON.parse( tmp.substr( 0, i + 1 ) );
function recursiveGetProperty(obj, lookup, callback) {
for (property in obj) {
if (property == lookup) {
callback(obj[property]);
} else if (obj[property] instanceof Object) {
recursiveGetProperty(obj[property], lookup, callback);
}
}
}
就像這樣使用它:
recursiveGetProperty(yourObject, '_events', function(obj) {
// do something with it.
});
這是一個有效的 jsFiddle: http : //jsfiddle.net/ErHng/ (注意:它輸出到控制台,因此您需要在 chrome 中按 Ctrl+Shift+J / Cmnd+Option+I或在 Firefox 中打開 firebug,然后重新-運行)
我發現在這種情況下,最簡單的方法是轉到JSFiddle ,將您的 json 作為變量粘貼:
var json = {"baseball": ... etc.
console.log(json);
然后使用 Chrome,“查看”->“開發人員”->“Javascript 控制台”開始嘗試數據結構的外觀,以構建您的解析功能。
然后開始嘗試結構。 例如。
console.log(json.baseball.mlb.regular._events);
或者,如果您打開 JQuery:
$.each(json.baseball.mlb.regular._events, function(i, item){
$.each(item.lines,function(i,line){
console.log(line.coeff);
});
});
如果您在實際將此 JSON 加載到變量中時遇到問題,您需要對通過我懷疑的 AJAX 調用檢索的字符串進行 JSON.parse。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.