如何循环JSON对象?

时间:2010-06-11 11:38:56

标签: javascript json

我有这个JSON对象:

{"time":"123456789", "raw":"chat_history", "data":{
"msg":[
 {"time":1111111111, "user":"user1", "text":"text from user1"},
 {"time":2222222222, "user":"user2", "text":"text from user2"},
 {"time":3333333333, "user":"user3", "text":"text from user3"},
 {"time":4444444444, "user":"user4", "text":"text from user4"}
]
}}

我必须创建一个FOR来循环data.msg的元素并打印它:

我会用FOR:

打印这些结果
11111111111 - user1 - text from users1
22222222222 - user2 - text from users2
33333333333 - user3 - text from users3
44444444444 - user4 - text from users4

你能帮帮我吗?

非常感谢

2 个答案:

答案 0 :(得分:5)

for(var i = 0; i < data.msg.length; i++)
{
    var row = data.msg[i];
    print(row.time + ' - ' + row.user + ' - ' + row.text);
}

答案 1 :(得分:0)

var msg = yourJsonObject.data.msg;

for (var i = 0, len = msg.length; i < len; i++) {
  // document.write only for example
  document.write(msg[i].time + ' - ' + msg[i].user + ' - ' + msg[i].text);
}