Reputation: 9
I have a JSON file in which is stored a list of regions that I want to get dynamically using JavaScript and JQuery. here's the an example of the content of my file :
{"Regions":
[
"Region":{
"type":"polyline",
"title":"Region 1",
"strokeColor":"#000000",
"strokeOpacity":1,
"strokeWeight":3,
"path":[{"lat":"21.32008096400822","lng":"79.376220703125"},{"lat":"21.524627220545295","lng":"80.48583984375"},{"lat":"20.488773287109833","lng":"80.2001953125"},{"lat":"20.427012814257385","lng":"79.552001953125"},{"lat":"20.612219573881042","lng":"79.112548828125"},{"lat":"21.32008096400822","lng":"79.376220703125"}]
},"Region":{
"type":"polyline",
"title":"Region 2",
"strokeColor":"#000000",
"strokeOpacity":1,
"strokeWeight":3,
"path":[{"lat":"21.32008096400822","lng":"79.376220703125"},{"lat":"21.524627220545295","lng":"80.48583984375"},{"lat":"20.488773287109833","lng":"80.2001953125"},{"lat":"20.427012814257385","lng":"79.552001953125"},{"lat":"20.612219573881042","lng":"79.112548828125"},{"lat":"21.32008096400822","lng":"79.376220703125"}]
}
]
}
here's my JS code :
$.getJSON( "regions.json", function( data ) {
var regions = [];
$.each(data,function(key,value){
if(key=='Regions'){
regions=value;
$.each(regions,function(key,value){
if(key=='Region'){
alert(value);
}
});
}
});
});
When I test this code I get only one prompt , and I don't get the other regions .
Upvotes: 0
Views: 62
Reputation: 8499
Your JSON data is in wrong format, change 'Regions' to array:
{
"Regions": [
{
"type": "polyline",
"title": "Region 1",
"strokeColor": "#000000",
"strokeOpacity": 1,
"strokeWeight": 3,
"path": [
{
"lat": "21.32008096400822",
"lng": "79.376220703125"
},
{
"lat": "21.524627220545295",
"lng": "80.48583984375"
},
{
"lat": "20.488773287109833",
"lng": "80.2001953125"
},
{
"lat": "20.427012814257385",
"lng": "79.552001953125"
},
{
"lat": "20.612219573881042",
"lng": "79.112548828125"
},
{
"lat": "21.32008096400822",
"lng": "79.376220703125"
}
]
},
{
"type": "polyline",
"title": "Region 2",
"strokeColor": "#000000",
"strokeOpacity": 1,
"strokeWeight": 3,
"path": [
{
"lat": "21.32008096400822",
"lng": "79.376220703125"
},
{
"lat": "21.524627220545295",
"lng": "80.48583984375"
},
{
"lat": "20.488773287109833",
"lng": "80.2001953125"
},
{
"lat": "20.427012814257385",
"lng": "79.552001953125"
},
{
"lat": "20.612219573881042",
"lng": "79.112548828125"
},
{
"lat": "21.32008096400822",
"lng": "79.376220703125"
}
]
}
]
}
Upvotes: 2