简体   繁体   中英

Accessing Nested Objects in Json

I have a custom object which contains other items (ie arrays, strings, other types of objects).

I am not sure how to traverse the object to iterate and list all of the object types, keys, and values of the nested items.

Second to this issue I don't know how many levels of nesting there are (as the object is generated dynamically from the back-end and passed to me as one object).

Any ideas (and should I just use javascript/jQuery or both to do this most efficiently)?


Thanks I'll give the code a go. I am retrieving a result set from a webservice which returns a different set of columns (of differing datatypes) and rows each time. I don't know the names of the columns which is why I am trying to get the data however I can.

Depending on the datatype I will perform a different action (sum the amount, format it etc).

JSON-serialized objects contain a hierarchy, w/o any reference cycles, so it should be fairly straightforward to traverse, something like

function visit(JSONobj, f)
{ 
   for (var key in JSONobj)
   {
       var value = JSONobj[key];
       f(key,value);
       if (value instanceof Object)
           visit(value, f);
   }
}

where f is a function that does something with keys and values. (of course you could just write a function to do this directly).

What exactly are you trying to find within the object?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM