2

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

4
  • 4
    It would help a lot if you indented correctly. Commented Jul 1, 2011 at 0:09
  • Indentation accomplished Commented Jul 1, 2011 at 0:10
  • 1
    @SimpleCoder - almost ;) Commented Jul 1, 2011 at 0:12
  • Ah, jsFiddle has let me down... Commented Jul 1, 2011 at 0:14

2 Answers 2

6
$.each(jsonObject.data.posts, function(index, val){
    alert(val.Post.title); //Do what you want to the title
});
Sign up to request clarification or add additional context in comments.

4 Comments

HI! thnks for the reply. Doing what you suggest is giving me a "a is undefined" on debug... is it becouse it comes empty?
@pedrosss What is the object that holds the json data?
I was doing a $.getJSON('url-here', function(data) and retreiving the result as showed in the question...
ignore the comment before, i was using "data" as the jsonObject.. :P Thanks!!!!!!
2

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

Thanks for the answer, but it returns error since i dont know what to put in "dataObj", (im getting the json trough a url)
Your result should be a JSON data, you should use the JSON.parse() function to parse the data into an object. You can get the official JavaScript JSON library at JSON.org.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.