I have a jquery json object like:
{"meta":{"limit":20,"next":null,"offset":0,"previous":null,"total_count":2},
"objects":[
{"body":"Body 1","date":"2013-01-15},
{"body":"Body 2","date":"2013-02-25}
]}
I would like to display looped data:
body 1, date
body 2, date
-
could you maybe provide the HTML that you would like to display this information? have you thought of using a templating plugin?ShaneBlake– ShaneBlake2013年03月04日 13:35:41 +00:00Commented Mar 4, 2013 at 13:35
-
What the hell is a jQuery-JSON object? :Pyckart– yckart2013年03月04日 13:37:47 +00:00Commented Mar 4, 2013 at 13:37
-
2Also your json is invalid you need to close your date with " otherwise nothing will work ie "date":"2013年01月15日"Dominic Green– Dominic Green2013年03月04日 13:38:38 +00:00Commented Mar 4, 2013 at 13:38
-
You can try like this objects[0]["body"] hope it will workPeeyush– Peeyush2013年03月04日 13:41:16 +00:00Commented Mar 4, 2013 at 13:41
5 Answers 5
try this
var data= "yourjson";
$.each(data.objects,function(i,v){
alert(v.body);
alert(v.date);
});
had to correct some of the issues in the json.. like missing "... so please check the fiddle.
Comments
First of all, your JSON is invalid. You lack parentheses after date. This is a valid JSON:
var json = {"meta":{"limit":20,"next":null,"offset":0,"previous":null,"total_count":2},
"objects":[
{"body":"Body 1","date":"2013-01-15"},
{"body":"Body 2","date":"2013-02-25"}
]};
Please note the " sign after '2013-01-15' and after '2013-02-25'.
You can display 'body' and 'date' using JQuery's .each():
$.each(json.objects, function (index, obj) {
console.log(obj.body + " " + obj.date);
});
Comments
You need to fix your json first as it is invalid as your not closing your date with "
{
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 2
},
"objects": [
{
"body": "Body 1",
"date": "2013-01-15"
},
{
"body": "Body2",
"date": "2013-02-25"
}
]
}
Then something like this should work
$.each(data.objects[0],function(i,v){
alert(v.body+" - "+v.date);
}
Comments
var data = {"meta":{"limit":20,"next":null,"offset":0,"previous":null,"total_count":2},
"objects":[
{"body":"Body 1","date":"2013-01-15"},
{"body":"Body 2","date":"2013-02-25"}
]};
for(var i = 0; i < data.objects.length; i++){
alert(data.objects[i].body);
alert(data.objects[i].date);
}
Comments
JSON objects are like key-value pairs.
Suppose this whole JSON object is in variable data then to read the content, do the following.
meta is an object containing different data, so to read limit, next and others you have to use data.meta.limit and so on.
Now objects is array type in which there are different objects.
So to read body, execute data.objects[0].body and so on.