使用JavaScript / jQuery迭代JSON

时间:2015-09-23 18:22:02

标签: javascript jquery html json

我希望有人能够告诉我如何使用JavaScript / jQuery迭代下面提供的JSON,以便我可以使用jQuery为每条消息添加一个新的<li>

[
{
"id":2,
"chat_id":"wrz",
"sender":"Brandon",
"receiver":"Elliott",
"message":"This is a second test message.",
"created_at":"2015-09-21 00:00:00",
"updated_at":"2015-09-21 00:00:00",
"time_stamp":"2015-09-21 06:33:58"
},
{
"id":4,
"chat_id":"wrz",
"sender":"Elliot",
"receiver":"Brandon",
"message":"This is a third test message.",
"created_at":"2015-09-21 00:00:00",
"updated_at":"2015-09-21 00:00:00",
"time_stamp":"2015-09-21 06:33:58"
},
{
"id":5,
"chat_id":"wrz",
"sender":"Brandon",
"receiver":"Elliott",
"message":"This is a fourth test message.",
"created_at":"2015-09-21 00:00:00",
"updated_at":"2015-09-21 00:00:00",
"time_stamp":"2015-09-21 06:33:58"
}
]

3 个答案:

答案 0 :(得分:2)

HTML

 <ul id="containsMessages">
</ul>

的Javascript

var json = 
[
{
"id":2,
"chat_id":"wrz",
"sender":"Brandon",
"receiver":"Elliott",
"message":"This is a second test message.",
"created_at":"2015-09-21 00:00:00",
"updated_at":"2015-09-21 00:00:00",
"time_stamp":"2015-09-21 06:33:58"
},
{
"id":4,
"chat_id":"wrz",
"sender":"Elliot",
"receiver":"Brandon",
"message":"This is a third test message.",
"created_at":"2015-09-21 00:00:00",
"updated_at":"2015-09-21 00:00:00",
"time_stamp":"2015-09-21 06:33:58"
},
{
"id":5,
"chat_id":"wrz",
"sender":"Brandon",
"receiver":"Elliott",
"message":"This is a fourth test message.",
"created_at":"2015-09-21 00:00:00",
"updated_at":"2015-09-21 00:00:00",
"time_stamp":"2015-09-21 06:33:58"
}
];

$.each(json,function(index,item)
{
     $("#containsMessages").append("<li>"+item.message+"</li>");
});

答案 1 :(得分:0)

假设json存储在变量中,您可以执行以下操作(粗略示例其余部分取决于您:)):

var json = []; //Your json.
var $ul = $("#yourUl");
for (var i = 0; i < json.length; i++) {
    $ul.append($("<li />", {html: json[i].message}));
}

答案 2 :(得分:0)

以下是parseJSON()

的一种可能解决方案
var inputJSON = '[{"id":2,"chat_id":"wrz","sender":"Brandon","receiver":"Elliott","message":"This is a second test message.","created_at":"2015-09-21 00:00:00","updated_at":"2015-09-21 00:00:00","time_stamp":"2015-09-21 06:33:58"},{"id":3,"chat_id":"wrz","sender":"Brandon","receiver":"Elliott","message":"This is a third test message.","created_at":"2015-09-21 00:00:00","updated_at":"2015-09-21 00:00:00","time_stamp":"2015-09-21 06:33:58"}]';

var javascriptObject = jQuery.parseJSON(inputJSON);
var list = javascriptObject.map( function(json) { return '<li>'+json.message+'</li>'; } );
$('#list').append(list);

fiddle demo