如何自动解析JSON并获得变量中的所有键值对?



我试图动态创建一个数据库,没有硬编码所有的API响应值的列和行,所以我想学习如何通过JSON自动解析,并把所有的键/值在一个变量,所以我可以通过排序,并把它们放在db。

假设JSON是这样的:

(修改了destiny 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"下的一切。它会进入数据库,例如:

tbody> <<tr>
displayNameisPublic
Name1
Name2

Dmitry Torba在Get一个嵌套字典的所有键上发布了一个函数,它可以做你想做的事情。

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)

我尝试过这种方法,如果给定字典中有列表类型怎么办?

CallPretty.py

def JsonPrint(response, response_Keys):
print()
print(response_Keys)
for i in range(len(response_Keys)):
if type(response[response_Keys[i]]) == list:
print()

for j in range(len(response[response_Keys[i]])):
if type(response[response_Keys[i]][j]) == dict:
JsonPrint(response[response_Keys[i]][j], list(response[response_Keys[i]][j].keys()))
elif type(response[response_Keys[i]]) == dict:
JsonPrint(response[response_Keys[i]], list(response[response_Keys[i]].keys()))
else:
print(response_Keys[i], ':')
for j in range(len(response[response_Keys[i]].split('n'))):
print('t', response[response_Keys[i]].split('n')[j])

最新更新