Note that there are some explanatory texts on larger screens.

plurals
  1. POCheck if JSON keys/nodes exist
    primarykey
    data
    text
    <p>I'm using the Google Map API to retrieve city + state/region information from a postal code lookup. The issue is that in some cases a postal code lookup won't retrieve a city name. An example is 92625 (U.S).</p> <pre><code>var g = new GClientGeocoder(); g.setBaseCountryCode('US'); g.getLocations('92625', function(response){ if (response) { var place = response.Placemark[0]; var state = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName; var city = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName; GLog.write("City = "+city+" : State/Region = "+state+" : Country = " + g.getBaseCountryCode()); } }); </code></pre> <p>In certain cases, as mentioned above, there won't be a city name in the result so there will be an undefined error for city, because the key Locality does not exist. This error prevents the rest of the script from running.</p> <p>I was able to remedy it by...</p> <pre><code> if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality != null) var city = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName; else var city = ''; </code></pre> <p>...but this has me paranoid about a similar error for other keys. Eg: If AdministrativeArea is undefined the above IF statement would also cause an undefined error. So should I be checking to see if every Key/Node exists? Seems to be a messy approach because some of these keys are 5+ levels deep...is there an easier way to go about it, maybe some JQuery method I'm not familiar with?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload