【问题标题】:How to automatically parse JSON and get all key value pairs in a variable?如何自动解析 JSON 并获取变量中的所有键值对?
【发布时间】:2021-12-10 01:13:40
【问题描述】:

我正在尝试动态创建数据库,而无需对列和行的所有 API 响应值进行硬编码,因此我想学习如何通过 JSON 自动解析并将所有键/值放入变量中,以便进行排序通过并将它们放入数据库中。

假设我有一些这样的 JSON:

(从命运 2 API 响应中修改 sn-p,缩进 5)

{
     "Response": {
          "profile": {
               "data": {
                    "userInfo": {
                         "crossSaveOverride": 1,
                         "applicableMembershipTypes": [
                              3,
                              1
                         ],
                         "isPublic": true,
                         "membershipType": 1,
                         "membershipId": "123",      
                         "displayName": "Name1",
                         "bungieGlobalDisplayName": "name again",
                         "bungieGlobalDisplayNameCode": 0000
                    },
                    "dateLastPlayed": "2021-6-18T02:33:01Z",        
                    "versionsOwned": 127,
                    "characterIds": [
                         "id1",
                         "id2",
                         "id3"
                    ],
                    "seasonHashes": [
                         3243434344,
                         3423434244,
                         3432342443,
                         3434243244
                    ],
                    "currentSeasonHash": 3434243244,
                    "currentSeasonRewardPowerCap": 1330
               },
               "privacy": 1
          }
     },
     "ErrorCode": 1,
     "ThrottleSeconds": 0,
     "ErrorStatus": "Success",
     "Message": "Ok",
     "MessageData": {}
}

我想自动解析并获取所有键/值减去错误代码区域,以便 "Response" 下的所有内容。例如,它将全部进入数据库:

displayName isPublic
Name1 True
Name2 False

我知道如何正常解析或循环,但只能获取如下值:

displayName = Response["Response"]["profile"]["data"]["userInfo"]["displayName"]

如何获取所有键和值,然后从最低级别自动存储到变量中?另外,如果不需要键,如何排除它们?

编辑:添加说明

我了解到这个 JSON 响应类型是一个 dict,我可以使用 Response.keys()Response.values() 来获取键和值。

我要问的是,从Response["Response"] 开始,如何将所有键和值降到底层并排除我不需要的。

例如,如果我这样做:

r = Response["Response"] 
for key in r.keys():
    print(key)

我只会得到profile,这是我不需要的。

我必须这样做:

r = Response["Response"]["profile"]["data"]["userInfo"] 
for key in r.keys():
    print(key)

会返回

crossSaveOverride
applicableMembershipTypes
isPublic
membershipType
membershipId
displayName
bungieGlobalDisplayName
bungieGlobalDisplayNameCode

这是我需要的,但我不想手动定义 ["Response"]["profile"]["data"]["userInfo"] 或类似的每个响应。我想自动抓取所有东西,同时排除我不需要的物品。

【问题讨论】:

  • 你可以尝试使用json模块。 import json 然后使用json.loads 函数。
  • “获取所有键/值”到底是什么意思? IE。如何以及以什么形式?
  • @martineau 例如,解析并获取 displayName 和值 Name1。我可以得到值“Name1”,但我不知道如何获取字符串“displayname”本身。我相信将所有内容都放入 dict 中会起作用,但我不知道。
  • 我不确定我是否正确理解了您的问题,但要获取所有密钥,您可以使用response.keys()
  • 您可以像@sushant 建议的那样使用json.load() 将JSON 转换为Python 字典,但这并不能回答我的问题,既然您拥有该字典,那么您想如何获取所有内容当您在字典中基本上已经有了它时,其中的键/值对 - 所以不清楚您的意思。

标签: python json python-3.x api parsing


【解决方案1】:

Dmitry Torba 在Get all keys of a nested dictionary 发布了一个功能,可以满足您的需求。

def recursive_items(dictionary):
    for key, value in dictionary.items():
        if type(value) is dict:
            yield from recursive_items(value)
        else:
            yield (key, value)

a = {'a': {1: {1: 2, 3: 4}, 2: {5: 6}}}

for key, value in recursive_items(a):
    print(key, value)

【讨论】:

  • 这如何消除“手动定义 ["Response"]["profile"]["data"]["userInfo"]" 的需要?
猜你喜欢
  • 1970-01-01
  • 2013-02-28
  • 1970-01-01
  • 1970-01-01
  • 2016-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多