简体   繁体   中英

access a deep Json element in a multidimentional JSON array

here is the code

var txt = '{"tblCommoHier":[ {"DEPT":[' + '{"DEPT":"100","DEPT_NAME":"Collectibles" },' + '{"DEPT":"105","DEPT_NAME":"Commodities" },' + '{"DEPT":"140","DEPT_NAME":"Souvenir" }]}]}';              
var obj = eval ("(" + txt + ")");

I'm trying the code

obj.tblCommoHier.DEPT[1].DEPT

to reach out to the first element of the DEPT element under tblCommoHier but I keep getting error says not defined.

Can somebody please help me with this issue?

In general, avoid using eval . The JSON object has a parse method for converting from strings to JSON. Also, when dereferencing an object nested in an array, you must remember your array indexing. The first two layers of your JSON object have array values. The correct formulation is:

var txt = '{"tblCommoHier":[ {"DEPT":[' + '{"DEPT":"100","DEPT_NAME":"Collectibles" },' + '{"DEPT":"105","DEPT_NAME":"Commodities" },' + '{"DEPT":"140","DEPT_NAME":"Souvenir" }]}]}';

var obj = JSON.parse(txt);

var elem = obj.tblCommoHier[0].DEPT[0].DEPT;

This yields "100" .

You want

obj.tblCommoHier[0].DEPT[0].DEPT

That will yield "100"

If you are using jQuery you should use $.parseJSON instead of eval .

tblCommoHier is an array itself, so you should use:

obj.tblCommoHier[0].DEPT[1].DEPT

Take a look at this jsFiddle if you want to test anything

try this: http://jsfiddle.net/jbTLB/

var txt = '{"tblCommoHier":[ {"DEPT":[' + '{"DEPT":"100","DEPT_NAME":"Collectibles" },' + '{"DEPT":"105","DEPT_NAME":"Commodities" },' + '{"DEPT":"140","DEPT_NAME":"Souvenir" }]}]}';
var obj = $.parseJSON(txt);
console.log(obj.tblCommoHier[0].DEPT[0].DEPT);
    //-----------------------------------^------this will get the 100

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