如何解析具有多个对象的JSON文件

时间:2019-05-30 10:28:43

标签: python json

我正在尝试解析一个包含多个JSON对象的JSON文件。这是我的代码:

{
    "obj1": {
        "type": "object", 
        "permission": "r",
        "obj2": {
            "type": "param", 
            "permission": "r/w"
        }, 
        "obj3": {
            "type": "param", 
            "permission": "r"
        }, 
        "obj4": {
            "type": "object", 
            "permission": "r",
            "obj5": {
                "type": "param", 
                "permission": "r/w"
            }, 
            "obj6": {
                "type": "param", 
                "permission": "r"
            },
            "obj7": {
                "type": "object", 
                "permission": "r",
                "obj8": {
                    "type": "param", 
                    "permission": "r/w"
                }, 
                "obj9": {
                    "type": "param", 
                    "permission": "r"
                }
            }
        }
    }
}

我曾尝试使用JSON提取单个对象解析响应。但是我不知道如何解析具有多个节点的JSON对象。

对于每个JSON对象,我也不知道其名称(obj1,obj2,..)

我想要输出结果:

obj1: has 2 param and 1 object
obj2: has 2 param and 1 object
obj3: has 2 param

python是否可以解析具有多个对象的JSON文件?

1 个答案:

答案 0 :(得分:0)

尝试一下:

op = json.loads(json_string)
for i,(key,value) in enumerate(op.items()):
    objects = 0
    params = len(value)
    if isinstance(value,dict):
        for k,v in value.items():
            if isinstance(v,dict):
                objects +=1



    print("Object {i} has {params} params and {objects} objects".format(i=i+1,params=params-objects,objects=obj