开发者

how to skip undefined properties in JSON?

开发者 https://www.devze.com 2023-01-21 09:25 出处:网络
When I parse JSON fields coming from google maps, etc., it is a mess. Because they are not made spec开发者_运维知识库ifically for my script I have to verify many details, epecially because the address

When I parse JSON fields coming from google maps, etc., it is a mess. Because they are not made spec开发者_运维知识库ifically for my script I have to verify many details, epecially because the addresses are different in every country.

Short question: when the script finds a undefined property the script breaks...error..

How can I verify the property is defined?

if(data.Placemark[i].AddressDetails.Country
       .AdministrativeArea.SubAdministrativeArea.Locality != null) {
         /***do something***/
}

Something like that doesn't seem to solve the problem. Why?


In JavaScript, accessing a property of an object that does not exist returns undefined, not null - heck, you said it in the title.

So, assuming that all the previous properties do actually exist, you can check that the Locality property exists using typeof, like this:

if(typeof (data.
           Placemark[i].
           AddressDetails.
           Country.
           AdministrativeArea.
           SubAdministrativeArea.
           Locality) !== 'undefined') {
    /***do something***/
}

Or, (I think) you can use hasOwnProperty():

if (data.
    Placemark[i].
    AddressDetails.
    Country.
    AdministrativeArea.
    SubAdministrativeArea.hasOwnProperty('Locality'))
{
    /*** do something ***/
}


First, In javascript you can use "try / catch" like java or other programming language, this can let your code continue running if something goes wrong...

for your issue, you can test that :

if (typeof(data.Placemark[i].AddressDetails.Country
               .AdministrativeArea.SubAdministrativeArea.Locality) 
    &&
      data.Placemark[i].AddressDetails.Country
               .AdministrativeArea.SubAdministrativeArea.Locality.length>0) {
}
0

精彩评论

暂无评论...
验证码 换一张
取 消