michael
michael

Reputation: 3

JQuery: GetJson give me only undefined data

I'm trying to parse a JSON result with this script:

$.getJSON( url, function(data){
    var items=[];
    $.each(data,function(i,item){
        items.push("<div class='col-lg-12' >");
        items.push( " By "+ item.user_name +": "+ item.created_at);                
        items.push("</div>");
        items.push("<div class='col-lg-12' >");
        items.push( "<p>" + item.text + "</p>" );                
        items.push("</div>");
    });
    $( "<ul/>", {
        "class": "my-new-list",
        html: items.join( "" )
    }).appendTo( "#commentaires" );
});

The JSON to parse is

[
    [
        {
            "text": "text1",
            "created_at": "12 May, 2015",
            "user_name": "gilbert moignon"
        }
    ],
    [
        {
            "text": "text2",
            "created_at": "12 May, 2015",
            "user_name": "jean bono"
        }
    ],
    [
        {
            "text": "text3",
            "created_at": "12 May, 2015",
            "user_name": "gerard mentor"
        }
    ]
]

Unfortunaltely, for an unknow reason, I only see undefined instead of my data. Can anyone help me?

Upvotes: 0

Views: 542

Answers (1)

Tushar
Tushar

Reputation: 87203

You have to change your code as follow:

Because you are parsing nested arrays and have only one element in array you have to use item[0] inside each:

$.each(data, function (i, item) {
    item = item[0];

Demo: https://jsfiddle.net/tusharj/dydect3t/

Upvotes: 1

Related Questions