首页 > 解决方案 > 如何在python中使用pandas从动态JSON对象中获取所有键

问题描述

我从多个 web 服务中得到一个复杂的 JSON 响应。我需要使用 python 获取各个级别的所有键。要使用 JSON_NORMALISE 我需要知道键名。由于我收到多个回复,我无法提供密钥名称。如果我在外层进行规范化,则较低级别的 json 不会转换为字典。它仍然是json格式。

{'Id': 123,
 'oldnumber': 1,
 'new number': 8,
 'version': 1,
 'newversion': 1,
 'personList':[{
         'id':1,
         'name': xyz,
         'marks':[{'phy':90,
                   'che':80
                 }
                {'bot':90,
                   'zoo':80
                 },
                 {'phy':60,
                   'che':80
                 }
                {'bot':20,
                   'zoo':80
                 }
                 ]}
         ],
'anotherList':[{
         'id':1,
         'data': xyz,
         'some':[{'not':90,
                   'dot':80
                 }
                {'cot':90,
                   'pot':80
                 },
                 {'ans':60,
                   'dog':80
                 }
                {'cat':20,
                   'mat':80
                 }
                 ]}
         ]
         } 

如何从我从响应中获得的 JSON 中读取所有键名?

标签: jsonpython-3.xpandasrestweb-services

解决方案


要从复杂的 JSON 对象中获取所有键,我们可以使用简单的 python 直接遍历 JSON 对象。我从下面的链接得到了解决方案。

参考 - https://towardsdatascience.com/flattening-json-objects-in-python-f5343c794b10

我稍微修改了代码,现在我可以从 JSON 中获取所有密钥

def normalise_json(y): out = set()

def normalise(x):
    if type(x) is dict:
        for a in x:
            out.add(a)
            normalise(x[a])
    elif type(x) is list:
        for a in x:
            normalise(a)

normalise(y)
return out

推荐阅读