pedrosss
pedrosss

Reputation: 57

JSON Loop using jquery

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

Upvotes: 2

Views: 2636

Answers (2)

Zachary
Zachary

Reputation: 6532

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

Upvotes: 2

The Scrum Meister
The Scrum Meister

Reputation: 30131

$.each(jsonObject.data.posts, function(index, val){
    alert(val.Post.title); //Do what you want to the title
});

Upvotes: 6

Related Questions