After reading some questions here, I still have difficulty on making a loop through my JSON results. Here they are:
{
"data": {
"posts": [
{
"Post": {
"id": "1",
"user_id": "1",
"title": "Test Content",
"created": "2011-06-30"
}
},
{
"Post": {
"id": "2",
"user_id": "2",
"title": "New Test Content",
"created": "2011-06-30"
}
}
]
}
}
How can I get Post.title using $.each() ?
Jonathan Hall
80.5k19 gold badges163 silver badges207 bronze badges
-
4It would help a lot if you indented correctly.sje397– sje3972011年07月01日 00:09:55 +00:00Commented Jul 1, 2011 at 0:09
-
Indentation accomplishedChris Laplante– Chris Laplante2011年07月01日 00:10:53 +00:00Commented Jul 1, 2011 at 0:10
-
1@SimpleCoder - almost ;)sje397– sje3972011年07月01日 00:12:52 +00:00Commented Jul 1, 2011 at 0:12
-
Ah, jsFiddle has let me down...Chris Laplante– Chris Laplante2011年07月01日 00:14:13 +00:00Commented Jul 1, 2011 at 0:14
2 Answers 2
$.each(jsonObject.data.posts, function(index, val){
alert(val.Post.title); //Do what you want to the title
});
answered Jul 1, 2011 at 0:11
The Scrum Meister
30.2k8 gold badges69 silver badges65 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
pedrosss
HI! thnks for the reply. Doing what you suggest is giving me a "a is undefined" on debug... is it becouse it comes empty?
The Scrum Meister
@pedrosss What is the object that holds the json data?
pedrosss
I was doing a $.getJSON('url-here', function(data) and retreiving the result as showed in the question...
pedrosss
ignore the comment before, i was using "data" as the jsonObject.. :P Thanks!!!!!!
Here is a example using jsFiddle.
Example target to output values:
<div id="output"></div>
jQuery Call to Object, iterate over "posts".
/* Create an Object from your JSON data, added based on comment about return results via URL */
var dataObj = JSON.parse(<put your JSON data here>);
$.each(dataObj.data.posts, function(idx, val) {
/* Show ID */
$('#output').append($('<p></p>').html('ID = ' + val.Post.id));
/* Show Title */
$('#output').append($('<p></p>').html('Title = ' + val.Post.title));
});
2 Comments
pedrosss
Thanks for the answer, but it returns error since i dont know what to put in "dataObj", (im getting the json trough a url)
lang-js