parsing – how to skip undefined properties in JSON? – Education Career Blog

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.Placemarki.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.
           Placemarki.
           AddressDetails.
           Country.
           AdministrativeArea.
           SubAdministrativeArea.
           Locality) !== 'undefined') {
    /***do something***/
}

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

if (data.
    Placemarki.
    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.Placemarki.AddressDetails.Country
               .AdministrativeArea.SubAdministrativeArea.Locality) 
    &&
      data.Placemarki.AddressDetails.Country
               .AdministrativeArea.SubAdministrativeArea.Locality.length>0) {
}

Leave a Comment