hard time with JSON and google maps
It might be a frequent question but i cannot figure out how to prevent errors in my 开发者_JS百科parsing when the script can't find a property...
in XML was easy because even the empty properties were like <location/>
but now if location
is not available JSON paser cant find it and it results in errors...OR
it may happen the json has different property or a children lost its father..... so for instance if you need to extract the LocalityName
is no more under SubAdministrativeArea
but under AddressLine
...
any of you have any experience about? what the best way to solve it and to parse it correctly?
While answering one of your other question I had written the following javascript code to obtain the lat and lng from the JSON returned by the maps api without any validations for zero results.
$.getJSON("getjson.php?address="+address,
function(data){
lat=data.results[0].geometry.location.lat;
lng=data.results[0].geometry.location.lng;
//.....map initialization code
}
);
Now if I were to validate for zero results, I'd modify the code in the following way
$.getJSON("getjson.php?address="+address,
function(data){
if (data.result.length>0) {
for (count=0;count<data.result.length;count++){
lat=data.results[count].geometry.location.lat;
lng=data.results[count].geometry.location.lng;
//.....map initialization code
}
}
}
);
As you can see parsing JSON comes naturally to javascript and to many other languages for it resolves down to arrays/lists and objects/dictionary/hash.
If I get this right and you are using a library to convert to json like gson try to construct some kind of object array like arrayList in java and then convert to json so every object you retrieve later in javascript is distinct and thus clear during debugging.Also if you don't use firebug give it try as it shows json data clearly.cheers
精彩评论