2013-11-26 76 views
0

我正在尝试查看一个对象,但基于结构我不知道如何获取数据。在javascript中循环浏览json对象

对象:

{ 
"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); 
}); 

它返回undefined。我究竟做错了什么?

+0

什么是'data'是一个字符串? – qwertynl

+0

'obj [index] .text'? – Krishna

+0

数据是上述代码中显示的对象 – steeped

回答

0

要循环浏览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); 
}; 
+1

你应该非常小心地使用,而不必首先检查物体是否有财产。 –

+0

@DavidBarker是什么意思? – qwertynl

+1

_“它试图从页面中选择该json对象”_ - [不是不是。](http://api.jquery.com/jquery/#jQuery-object) – nnnnnn

0

其更好一点做这样的:

$.each(obj, function (index, note) { 
    console.log(note.text + note.user_name + note.date_created); 
}); 

这应该给你你需要什么

0

工作演示:http://jsfiddle.net/gZ7pd/for documenthttp://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); 
}); 
+0

@Downvoter谨慎回复为什么downvote? ':)'还是仅仅是个人选择而降低投票率?没有建设性! –

+1

你的例子完美无缺+1 – kkemple

+1

@kkemple谢谢bruvoo':)'很伤心有人不经意就失去了原意! Cheeerios哟! +1给你! –

1

尝试这样

var obj = $.parseJSON(data); 
for(var n in obj){ 
var note = obj[n] 
console.log(note.text + note.user_name + note.date_created); 
} 
+1

基本上我说的是:-P – qwertynl

+0

是的,你有点快。感谢您的投票:) – brunettdan