使用javascript或jQuery删除数组中包含空对象的键

时间:2015-04-13 04:49:58

标签: javascript jquery json

我想删除包含数组内空对象的JSON键...
这是我的 JSON 结构:

{
    "CreateSubnet": {
        "description": "Creatingasubnet.",
        "input": {
            "body": {
                "subnet": {
                    "network_id": "sdfsdfds",
                    "ip_version": "sdfdsfs",
                    "cidr": "sdfsdf",
                    "allocation_pools": [
                        {}
                    ]
                }
            }
        },
        "action": "neutron.create_network",
        "publish": {},
        "on-success": []
    }
}

请帮我删除元素"allocation_pools" ..
我从来不想要这个钥匙和这个价值......

预期输出JSON 看起来像......

{
    "CreateSubnet": {
        "description": "Creatingasubnet.",
        "input": {
            "body": {
                "subnet": {
                    "network_id": "sdfsdfds",
                    "ip_version": "sdfdsfs",
                    "cidr": "sdfsdf"
                }
            }
        },
        "action": "neutron.create_network",
        "publish": {},
        "on-success": []
    }
}

请注意,此JSON来自外部源,它会动态更改...
所以请告诉我如何验证JSON键包含数组...
如果是,请检查它是否有空物体。
这是我的问题

1 个答案:

答案 0 :(得分:-1)

使用delete运算符删除属性。



var obj = {
    "CreateSubnet": {
        "description": "Creatingasubnet.",
        "input": {
            "body": {
                "subnet": {
                    "network_id": "sdfsdfds",
                    "ip_version": "sdfdsfs",
                    "cidr": "sdfsdf",
                    "allocation_pools": [
                        {}
                    ]
                }
            }
        },
        "action": "neutron.create_network",
        "publish": {},
        "on-success": []
    }
}
delete (obj.CreateSubnet.input.body.subnet.allocation_pools);
document.getElementById("output").innerHTML = JSON.stringify(obj)

<div id="output"></div>
&#13;
&#13;
&#13;