【问题标题】:How to get all the keys from dynamic JSON object using pandas in python如何在python中使用pandas从动态JSON对象中获取所有键
【发布时间】:2020-07-07 14:17:42
【问题描述】:

我从多个 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 中读取所有键名?

【问题讨论】:

    标签: json python-3.x pandas rest web-services


    【解决方案1】:

    要从复杂的 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
    

    【讨论】:

      猜你喜欢
      • 2017-07-19
      • 1970-01-01
      • 2020-01-18
      • 2021-07-15
      • 2016-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多