Check if JSON keys/nodes exist Check if JSON keys/nodes exist json json

Check if JSON keys/nodes exist


Alternatively, you could make a function, that gives you defaults:

function valueOrDefault(val, def) {    if (def == undefined) def = "";    return val == undefined ? def : val;}

And then use it like this:

var place = response.Placemark[0];var state = valueOrDefault(place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName);var city  = valueOrDefault(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName);

Personally, I think it's a little nicer to write, than p00ya's proposal, although it's a little hacky fiddling around in undefined objects ... one could maybe change it to this:

function drill(p, a) { a = a.split(".");//add this for (i in a) {  var key = a[i];  if (p[key] == null)    return '';  p = p[key]; } return p;}var obj = {foo:{bar:{baz:"quux"}}};var s = drill(obj, "foo.bar.baz"));//and you can use a simple property chain


You could use a function that "drills" down through all those nesting levels, defaulting to the empty string if it can't get that far.

function drill(p, a) { for (i in a) {  var key = a[i];  if (p[key] == null)    return '';  p = p[key]; } return p;}var obj = {foo:{bar:{baz:"quux"}}};var s = drill(obj, ["foo", "bar", "baz"]));


I like back2dos' approach but I think it could be improved so as not to fail with ReferenceErrors:

function jPath(obj, a) {    a = a.split(".");    var p = obj||{};    for (var i in a) {        if (p === null || typeof p[a[i]] === 'undefined') return null;        p = p[a[i]];    }    return p;}// Testsvar a = {b:{c:'Hello World!'}, c:null};console.log(jPath(a, 'b.c'));   // Hello Worldconsole.log(jPath(a, 'b.d'));   // nullconsole.log(jPath(a, 'e.f.g')); // nullconsole.log(jPath(a, 'c'));     // nullvar z;console.log(jPath(z, 'c'));     // null

This kind of function is great for validating deep JSON return structures from AJAX services such as freebase or YQL.