Jerome Ansia
Jerome Ansia

Reputation: 6884

Json Loop Jquery each doesn't work "undefined"

I've got a problem with those data,

my json array data contains:

{"list_file":["{\"id\":\"511\",\"name\":\"Jellyfish.jpg\",\"projectId\":\"12539\",\"projectName\":\"project namessszd ddddzzde\",\"time\":\"1331843704\",\"size\":775702,\"timeRightFormat\":\"03\\\/15\\\/12 01:35:04 PM\",\"userFirstName\":\"Jerome\",\"userLastName\":\"Test\",\"userId\":\"8\"}","{\"id\":\"510\",\"name\":\"Hydrangeas.jpg\",\"projectId\":\"12539\",\"projectName\":\"project namessszd ddddzzde\",\"time\":\"1331843704\",\"size\":595284,\"timeRightFormat\":\"03\\\/15\\\/12 01:35:04 PM\",\"userFirstName\":\"Jerome\",\"userLastName\":\"Test\",\"userId\":\"8\"}","{\"id\":\"509\",\"name\":\"dudnzoizu ufoiuzio fueoifezuoiufifzeouofufzeoiuiofuz oife iofez.jpg\",\"projectId\":\"12539\",\"projectName\":\"project namessszd ddddzzde\",\"time\":\"1331843704\",\"size\":885242,\"timeRightFormat\":\"03\\\/15\\\/12 01:35:04 PM\",\"userFirstName\":\"Jerome\",\"userLastName\":\"Test\",\"userId\":\"8\"}"]}

when i loop through the elements like this

    $.each(data.list_file, function(i, file) {
        alert(file.id);
    });

I got undefined in the alert() box, but if i do just this instead

      $.each(data.list_file, function(i, file) {
        alert(file);
    });

I got the right json line.

Thank you

EDIT: with the entire array this time

Upvotes: 0

Views: 965

Answers (4)

Henrik Andersson
Henrik Andersson

Reputation: 47172

Enclose the JSON in [], it'll work then. What you have is a json list.

And check out this Tinker.io

If you parse the JSON you can then use the normal notation for accessing the objects properties.

Validate the json here!

Good luck!

Upvotes: 2

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

What you have inside list_file is a string and not an Object. Actually, you have 3 strings.. each an object... Try using a function like below,

$.each(data['list_file'], function(i, file) {
    alert(JSON.parse(file).id);
});

Upvotes: 1

Kevin B
Kevin B

Reputation: 95022

I'm assuming you are making an ajax call. You need to specify the "json" datatype so that jquery will parse it as json.

$.ajax({
    url: url,
    dataType: "json",
    success: function (data) {
        // ...
    }
})

UPDATE:

Your json array is an array of json strings, try changing that to an array of objects:

{ "list_file": [ "{...}" ]}

should be

{ "list_file": [ {...} ]}

Upvotes: 1

Royi Namir
Royi Namir

Reputation: 148524

this is not a valid json

you should wrap it with brackets !

you have many objects which must be in an Array.

Fix this first. later check.

Upvotes: 0

Related Questions