如何解析包含对象内数组的Json对象

时间:2013-08-13 16:35:40

标签: javascript jquery json

这是我的Json Object示例:

{"UserName":Mike,"IsActive":0,"ChbxIsActive":false,"MyAccountsAvailable":[{"Id":"157A","MyAccount":"CHRIS MCEL","MyCheckBox":false,"Tags":null},{"Id":"157B","MyAccount":"DAN BONE","MyCheckBox":false,"Tags":null}

继承我对部分目标的尝试:

$.getJSON('/ManageUsers/GetCheckBoxesJson', { clientId: clientId, user: user }, function (data) {
            var items = [];
            $.each(data, function (key, val) {

                alert(key + " " + val);

            });

当然,我成功从对象中的属性获取数据,但不确定如何迭代数组。我得到[对象,对象]如果有人可以展示一个很棒的样本。

1 个答案:

答案 0 :(得分:0)

您将需要一个嵌套循环来迭代数组:

$.each(data, function (key, val) {

    console.log(key + " " + val);

    if(key == 'MyAccountsAvailable') {
        $.each(val, function(subKey, subVal) {
            console.log(subKey + " " + subVal);
        });
    }

});

或直接访问值:

console.log( data.MyAccountsAvailable[0].Id );
console.log( data.MyAccountsAvailable[1].Id );

您可以检查值是否为数组,而不是测试密钥名称。有关如何执行此操作,请参阅this question