简体   繁体   中英

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

[
{
"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

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

Suppose that json is stored in a variable, you could do as follows (rough example the rest is up to you :)):

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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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