简体   繁体   English

使用JavaScript / jQuery遍历JSON

[英]Iterate through JSON with JavaScript/jQuery

I was hoping someone would be able to show me how to iterate through the provided JSON below with JavaScript/jQuery so that I can add a new <li> per message using jQuery 我希望有人能够向我展示如何使用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"
}
]

HTML 的HTML

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

Javascript Java脚本

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

Suppose that json is stored in a variable, you could do as follows (rough example the rest is up to you :)): 假设json存储在变量中,您可以执行以下操作(其余示例由您自己决定:)):

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

Here are one possible solution with parseJSON() 这是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 小提琴演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM