[英]Looping through a json object in javascript
我試圖查看一個對象,但是基於結構,我不知道如何獲取數據。
賓語:
{
"177":{
"text":"test text",
"user_name":"Admin",
"date":"1385494358",
"docs":{
"document_name": [
"marketing_service",
"maintenance_service",
"development_service"],
"document_type":[
"png",
"png",
"png"]
}
},
"174":{
"text":"Some more images",
"user_name":"Admin",
"date":"1385493618",
"docs":{
"document_name": [
"marketing_service16",
"maintenance_service53"],
"document_type":[
"png","png"]
}
}
}
我正在jQuery中嘗試的循環
var obj = $.parseJSON(data);
$(obj).each(function(index, note) {
console.log(note.text + note.user_name + note.date_created);
});
它返回未定義。 我究竟做錯了什么?
這樣嘗試
var obj = $.parseJSON(data);
for(var n in obj){
var note = obj[n]
console.log(note.text + note.user_name + note.date_created);
}
要遍歷json對象,只需使用for循環。
您執行此操作的方式將返回錯誤,因為它試圖從不存在的頁面中選擇該json對象。
樣例代碼:
var obj = $.parseJSON(data); //assuming `data` is a string
for(index in obj) {
var note = obj[index];
console.log(note.text + note.user_name + note.date_created);
};
這樣做是更好的一點:
$.each(obj, function ( index, note ) {
console.log( note.text + note.user_name + note.date_created );
});
這應該給你你所需要的
工作演示: http : //jsfiddle.net/gZ7pd/ 或 for document
http://jsfiddle.net/NGqfB/
問題是parseJson
對象是Json。
在上面的演示中, var obj = $.parseJSON(data);
返回null,如果我使用數據它將起作用。
希望這會有所幫助;)
碼
var data = {
"177":{
"text":"test text",
"user_name":"Admin",
"date":"1385494358",
"docs":{
"document_name": [
"marketing_service",
"maintenance_service",
"development_service"],
"document_type":[
"png",
"png",
"png"]
}
},
"174":{
"text":"Some more images",
"user_name":"Admin",
"date":"1385493618",
"docs":{
"document_name": [
"marketing_service16",
"maintenance_service53"],
"document_type":[
"png","png"]
}
}
};
var obj = $.parseJSON(data);
alert(obj)
$.each(data,function(index, note) {
alert(note.text + note.user_name + note.date_created);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.