解析具有未知值的JSON字典

时间:2016-11-21 15:47:54

标签: python json dictionary

我正在尝试处理JSON中的字典,如下所示:

{
    "Parameters": {
        "IP": "192.168.1.40",
        "TIMEOUT": 900,
        "mode": 0
    },

    "Device": {
        "sector01": {
            "nodes": ["node01", "node02"] 
        },
        "sector02": {
            "nodes": ["node01"]
        },
        "sector03": {
            "nodes": ["node01","node02","node03"]       
        }
    }
}

假设我没有关于存在多少个扇区和节点的信息,我想知道扇区的数量(以及每个扇区有多少个节点)。 我能够通过以下方式找到所有扇区:

len(data["Device"])

但是,在我的情况下,每个扇区的节点总数更重要。

2 个答案:

答案 0 :(得分:1)

您可以使用for-loop获取每个“扇区”(无论您拥有多少扇区),然后您可以在扇区中获取“节点”并检查len()

for key, val in data['Device'].items(): 
    print(key, len(val["nodes"]))

答案 1 :(得分:0)

import json

your_json = """{
        "Parameters": {
            "IP": "192.168.1.40",
            "TIMEOUT": 900,
            "mode": 0
        },

        "Device": {
            "sector01": {
                "nodes": ["node01", "node02"] 
            },
            "sector02": {
                "nodes": ["node01"]
            },
            "sector03": {
                "nodes": ["node01","node02","node03"]       
            }
        }
    }"""

your_dict = json.loads(your_json)
len_of_device = len(your_dict['Device'])
dict_len_of_sectors = {}
for key in your_dict['Device']:
    dict_len_of_sectors[key] = len(your_dict['Device'][key]['nodes'])

print(str(dict_len_of_sectors))

我建议在这里学习更多: https://docs.python.org/3/library/stdtypes.html?highlight=dict#dict