Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get nested JSON/object value without needing many intermediate checks?

suppose i have a complex json object x with mixed objects and arrays. Is there a simple or generic way to check if a variable is null or undefined within this object, such as:

if(x.a.b[0].c.d[2].e!=null) ....

instead of normally checking all the parent fields

if(x.a!=null 
&& x.a.b!=null
&& x.a.b[0]!=null
&& x.a.b[0].c!=null
&& x.a.b[0].c.d!=null
&& x.a.b[0].c.d[2]!=null
&& x.a.b[0].c.d[2].e!=null) ....
like image 872
konghou Avatar asked Jan 02 '13 04:01

konghou


People also ask

How do I access a nested object in JSON?

Accessing nested json objects is just like accessing nested arrays. Nested objects are the objects that are inside an another object. In the following example 'vehicles' is a object which is inside a main object called 'person'. Using dot notation the nested objects' property(car) is accessed.

How do I flatten a nested JSON object?

Flatten a JSON object: var flatten = (function (isArray, wrapped) { return function (table) { return reduce("", {}, table); }; function reduce(path, accumulator, table) { if (isArray(table)) { var length = table.

Can JSON objects be nested?

Objects can be nested inside other objects. Each nested object must have a unique access path. The same field name can occur in nested objects in the same document.


1 Answers

try {
   if(x.a.b[0].c.d[2].e!=null)
    //....
} catch (e) {
    // What you want 
}

Live DEMO

like image 120
gdoron is supporting Monica Avatar answered Oct 09 '22 17:10

gdoron is supporting Monica