我正在嘗試動態創建一個資料庫而不對列和行的所有 API 回應值進行硬編碼,所以我想學習如何通過 JSON 自動決議并將所有鍵/值放在一個變數中,以便我可以進行排序和放置他們在資料庫中。
假設我有一些這樣的 JSON:
(來自命運 2 API 回應的修改片段,縮進 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". 它會全部進入資料庫,例如:
| 顯示名稱 | 是公共的 |
|---|---|
| 姓名1 | 真的 |
| 姓名2 | 錯誤的 |
我知道如何正常決議或回圈,但只能獲取如下值:
displayName = Response["Response"]["profile"]["data"]["userInfo"]["displayName"]
如何獲取所有鍵和值,然后從最低級別自動存盤在變數中?另外,如果不需要鍵,如何排除鍵?
編輯:添加說明
I learned that this JSON response type is a dict and I can use Response.keys() and Response.values() to get the keys and values.
What I am asking is, from Response["Response"], how to get all of the keys and values down to the bottom level and exclude the ones I don't need.
For example if I do:
r = Response["Response"]
for key in r.keys():
print(key)
I'm only going to get profile which is what I don't need.
I would have to do:
r = Response["Response"]["profile"]["data"]["userInfo"]
for key in r.keys():
print(key)
which would return
crossSaveOverride
applicableMembershipTypes
isPublic
membershipType
membershipId
displayName
bungieGlobalDisplayName
bungieGlobalDisplayNameCode
Which is what I need but I do not want to manually define
["Response"]["profile"]["data"]["userInfo"]or similar for every response. I want to grab everything automatically while excluding the items I don't need.
uj5u.com熱心網友回復:
德米特里·托爾巴 (Dmitry Torba) 在獲取嵌套字典的所有鍵時發布了一個可以執行您想要的操作的函式。
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/335512.html
標籤:python json python-3.x api parsing
上一篇:從條件中獲取JSON值
