Francesco
Francesco

Reputation: 25239

how to skip undefined properties in JSON?

When I parse JSON fields coming from google maps, etc., it is a mess. Because they are not made specifically 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?

Upvotes: 1

Views: 1937

Answers (2)

Patrick Ferreira
Patrick Ferreira

Reputation: 2053

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) {
}

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359836

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 ***/
}

Upvotes: 3

Related Questions