如何在JSON中读取子对象的属性?

时间:2014-03-03 07:28:45

标签: javascript json

{
    "name": "Top Bar After Login",
    "cid": "9921",
    "position": "26",
    "properties": [{
        "propname": "ITEMCOUNT",
        "propvalue": "0"
    }, {
        "propname": "Display",
        "propvalue": "yes"
    }],
    "childs": [{
        "name": "Santosh",
        "cid": "10299",
        "properties": [{
            "propname": "Display",
            "propvalue": "yes"
        }, {
            "propname": "ITEMCOUNT",
            "propvalue": "0"
        }],
        "childs": []
    }]
}

如何在上面的JSON对象中读取子属性?

我试过这个例子Parse JSON in JavaScript?,但它并没有帮助我获取孩子的属性。

感谢您的帮助。

谢谢, 桑托什

2 个答案:

答案 0 :(得分:1)

如果您将上方的对象存储在变量中,请说出parsed_obj,那么您只需执行

parsed_obj.properties[0];

访问其第一个属性

parsed_obj.properties[1];

为第二个。

答案 1 :(得分:0)

你这样做了吗?

var source = '{"name": "Top Bar After Login", "cid": "9921", "position": "26", "properties": [{"propname": "ITEMCOUNT","propvalue": "0"},{"propname": "Display", "propvalue": "yes"}],    "childs": [{"name": "Santosh","cid": "10299","properties": [{"propname": "Display", "propvalue": "yes" }, { "propname": "ITEMCOUNT", "propvalue": "0"}], "childs": [] }]}';

var obj = JSON.parse(source);
console.log( obj.childs[0].name ); //outputs Santosh
console.log( obj.name );            //Top Bar After Login 
console.log( obj.properties[0].propname,  obj.properties[0].propvalue ); //ITEMCOUNT 0

希望它可以帮到你