boube
boube

Reputation: 3

Parsing json jquery

My request ajax with json_encode:

[{"idHome":"1","Photo":"home-1.jpg","Publier":"1"},
{"idHome":"2","Photo":"home2.jpg","Publier":"1"}, 
{"idHome":"3","Photo":"home3.jpg","Publier":"1"}]

var string = JSON.stringify(data);

var obj = $.parseJSON(string);

console.log(string);

var idHome = obj.idHome;

var photo = obj.Photo;


console.log(obj.idHome);

console.log(obj.Photo);

Problem with parsing json

console log :

[{"idHome":"1","Photo":"home-1.jpg","Publier":"1"},{"idHome":"2","Photo":"home-2.jpg","Publier":"1"},{"idHome":"3","Photo":"home-3.jpg","Publier":"1"}]

undefined

undefined

Upvotes: 0

Views: 74

Answers (2)

PSL
PSL

Reputation: 123739

It is an array so you need to loop through, there are so many ways to do it.

for (i = 0; i < obj.length; i++) {
    console.log(obj[i].idHome);
    console.log(obj[i].Photo);
}

or:

obj.forEach(function(val) {
    console.log(val.idHome);
    console.log(val.Photo);
});

or:

for (var i in obj) {
    console.log(obj[i].idHome);
    console.log(obj[i].Photo);
}

Jquery use :

 $.each(obj, function(_, val){
    console.log(val.idHome);
    console.log(val.Photo);
 });

and so on....

Upvotes: 2

Rob
Rob

Reputation: 5588

Your json is an array of three objects.

Try

console.log(obj[0].idHome);
console.log(obj[0].Photo);

More info: http://www.w3schools.com/json/json_syntax.asp

Upvotes: 2

Related Questions