Вопрос

I'm going to traverse all post elements in this json response body using jQuery .each operator.

{
"posts": [
    {
        "Post": {
            "post_id": "1",
            "url": "somUrl",
            "image": "",
            "body": "textbody",
            "parent_id": "0",
            "title": "title1"
        }
    },
    {
       "Post": {
            "post_id": "2",
            "url": "somUrl",
            "image": "",
            "body": "textbody",
            "parent_id": "0",
            "title": "title2"
        }
        }
    },
    {
        "Post": {
            "post_id": "3",
            "url": "somUrl",
            "image": "",
            "body": "textbody",
            "parent_id": "0",
            "title": "title3"
        }
    },
    {
        "Post": {
            "post_id": "4",
            "url": "somUrl",
            "image": "",
            "body": "textbody",
            "parent_id": "0",
            "title": "title4"
        }
    }
]}

I wrote this code but it's not able to print the titles. It doesn't loop through the post items.

What should I do to make this code work?

data is the response variable that is passed to the callback function of ajax.

$.each(data,function(key,post){console.log(post.title)});

Thanks for any help.

Это было полезно?

Решение

The way that you are trying to access the json is wrong. Please think in the perspective of iterating an array of json.

Try,

$.each(data.posts , function(index,val){
   console.log(val.Post.title)
});

DEMO

Другие советы

at the place of data use data.posts

$.each(data.posts,function(key,val){
               console.log(val.post.title);
});

i think this will help you

$.each(data.posts,function(index,value){console.log(value.post.title)});

this should work, tested on fiddle:

$.each(data.posts,function(index,item){

console.log(item.Post);

});

for accessing specific property:

console.log(item.Post.propertyName);

for example:

 console.log(item.Post.title);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top