Reputation: 115
Hello I have a PHP script that returns the following JSON :
[
{
"zone_name": "1st_zone"
},
{
"coordinates": [
"51.56256,-0.37903",
"51.50789,-0.19913",
"51.58475,-0.06729",
"51.61461,-0.19638",
"51.5711,-0.28152"
]
},
{
"zone_name": "2nd_zone"
},
{
"coordinates": [
"51.56256,-0.37903",
"51.50789,-0.19913",
"51.58475,-0.06729",
"51.61461,-0.19638",
"51.5711,-0.28152",
"51.57707,0.11398",
"51.48651,0.12497",
"51.56939,0.28427"
]
}
]
In Javascript I'm doing an AJAX call like that :
$.ajax({
type: "POST",
cache: false,
url: "load_zone.php",
dataType: 'json',
success:function(response){
for(var i =0; i<response.length; i++){
console.log(response[i]);
}
},
error:function(){
}
});
I get this result in console :
Object { zone_name="1st_zone"}
Object { coordinates=[5]}
Object { zone_name="2nd_zone"}
Object { coordinates=[8]}
How can I print each zone_name and coordinates separately?
Thanks
Upvotes: 1
Views: 55
Reputation: 415
for(var i =0; i<response.length; i++){
if(i%2 === 0) console.log(response[i].zone_name);
else console.log(response[i].coordinates);
// console.log(response[i].zone_name || response[i].coordinates); //one liner
}
This will give you the respective zone names and coordinates. Your current JSON has an array of objects which list the zone names and coordinates as successive elements of the array.
But you should try to change your json to look something like this:
[
{
"zone_name": "1st_zone"
"coordinates": [
"51.56256,-0.37903",
"51.50789,-0.19913",
"51.58475,-0.06729",
"51.61461,-0.19638",
"51.5711,-0.28152"
]
}
...
]
Which will mean that the array would contain objects representing a zone with its coordinates. Which can then be accessed like response[i].zone_name
and response[i].coordinates
.
Upvotes: 1
Reputation: 62498
do like this:
$.each(data,function(index,item){
console.log(item);
$.each(item,function(index1,item1){
console.log(item1);
});
Upvotes: 0