访问多维JSON数组中的深Json元素

时间:2012-12-26 17:19:29

标签: javascript jquery json

这是代码

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

我正在尝试代码

obj.tblCommoHier.DEPT[1].DEPT

触及 tblCommoHier 下的 DEPT 元素的第一个元素,但我一直收到错误,说明没有定义。

有人可以帮我解决这个问题吗?

4 个答案:

答案 0 :(得分:4)

一般情况下,请避免使用evalJSON对象具有parse方法,用于将字符串转换为JSON。此外,在取消引用嵌套在数组中的对象时,您必须记住数组索引。 JSON对象的前两层具有数组值。正确的表述是:

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;

这会产生"100"

答案 1 :(得分:2)

你想要

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

这将产生“100”

如果您使用的是jQuery,则应使用$.parseJSON代替eval

答案 2 :(得分:2)

tblCommoHier本身就是一个数组,所以你应该使用:

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

如果您想测试任何内容,请查看此jsFiddle

答案 3 :(得分:0)

试试这个: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