我正在呼叫 API 并得到如下回應。
{
"status": 200,
"errmsg": "OK",
"data": {
"total": 12,
"items": [{
"id": 11,
"name": "BBC",
"priority": 4,
"levelStr": "All",
"escalatingChainId": 3,
"escalatingChain": {
"inAlerting": false,
"throttlingAlerts": 20,
"enableThrottling": true,
"name": "Example123",
"destination": [],
"description": "",
"ccdestination": [],
"id": 3,
"throttlingPeriod": 10
}
},
{
"id": 21,
"name": "CNBC",
"priority": 4,
"levelStr": "All",
"escalatingChainId": 3,
"escalatingChain": {
"inAlerting": false,
"throttlingAlerts": 20,
"enableThrottling": true,
"name": "Example456",
"destination": [],
"description": "",
"ccdestination": [],
"id": 3,
"throttlingPeriod": 10
}
}
]
}
}
我需要稍微清理一下這個 JSON 并生成一個簡單的 JSON,如下所示,串列中的escalatingChainName位置,以便我可以將其寫入 CSV 檔案。nameescalatingChain
{
"items": [{
"id": 11,
"name": "BBC",
"priority": 4,
"levelStr": "All",
"escalatingChainId": 3,
"escalatingChainName": "Example123"
},
{
"id": 21,
"name": "CNBC",
"priority": 4,
"levelStr": "All",
"escalatingChainId": 3,
"escalatingChainName": "Example456"
}
]
}
是否有一個 JSON 函式可用于僅將必要的鍵值或嵌套鍵值復制到新的 JSON 物件?
使用以下代碼,我可以獲得詳細資訊串列。
json_response = response.json()
items = json_response['data']
details = items['items']
我可以使用列印單個串列項
for x in details:
print(x)
我如何從這里只提取必要的欄位,如 id、name、priority 和 nameescalatingchain來創建新串列或 JSON?
uj5u.com熱心網友回復:
沒有現有的功能可以滿足您的需求,因此您需要撰寫一個。幸運的是,在這種情況下這并不太難——基本上,您只需通過從現有資料中提取所需的資料片段來創建新專案串列。
import json
json_response = """\
{
"status": 200,
"errmsg": "OK",
"data": {
"total": 12,
"items": [{
"id": 11,
"name": "BBC",
"priority": 4,
"levelStr": "All",
"escalatingChainId": 3,
"escalatingChain": {
"inAlerting": false,
"throttlingAlerts": 20,
"enableThrottling": true,
"name": "Example123",
"destination": [],
"description": "",
"ccdestination": [],
"id": 3,
"throttlingPeriod": 10
}
},
{
"id": 21,
"name": "CNBC",
"priority": 4,
"levelStr": "All",
"escalatingChainId": 3,
"escalatingChain": {
"inAlerting": false,
"throttlingAlerts": 20,
"enableThrottling": true,
"name": "Example456",
"destination": [],
"description": "",
"ccdestination": [],
"id": 3,
"throttlingPeriod": 10
}
}
]
}
}
"""
response = json.loads(json_response)
cleaned = []
for item in response['data']['items']:
cleaned.append({'id': item['id'],
'name': item['name'],
'priority': item['priority'],
'levelStr': item['levelStr'],
'escalatingChainId': item['escalatingChainId'],
'escalatingChainName': item['escalatingChain']['name']})
print('cleaned:')
print(json.dumps(cleaned, indent=4))
uj5u.com熱心網友回復:
你可以試試:
data = {
"status": 200,
"errmsg": "OK",
"data": {
"total": 12,
"items": [{
"id": 11,
"name": "BBC",
"priority": 4,
"levelStr": "All",
"escalatingChainId": 3,
"escalatingChain": {
"inAlerting": False,
"throttlingAlerts": 20,
"enableThrottling": True,
"name": "Example123",
"destination": [],
"description": "",
"ccdestination": [],
"id": 3,
"throttlingPeriod": 10
}
},
{
"id": 21,
"name": "CNBC",
"priority": 4,
"levelStr": "All",
"escalatingChainId": 3,
"escalatingChain": {
"inAlerting": False,
"throttlingAlerts": 20,
"enableThrottling": True,
"name": "Example456",
"destination": [],
"description": "",
"ccdestination": [],
"id": 3,
"throttlingPeriod": 10
}
}
]
}
}
for single_item in data["data"]["items"]:
print(single_item["id"])
print(single_item["name"])
print(single_item["priority"])
print(single_item["levelStr"])
print(single_item["escalatingChain"]["inAlerting"])
# and so on
uj5u.com熱心網友回復:
根據您是.json使用python串列和字典理解處理變數還是檔案,有兩種方法可以解決這個問題:
其中字典型別(嵌套)的資料變數已經定義:
# keys you want to_keep = ['id', 'name', 'priority', 'levelStr', 'escalatingChainId', 'escalatingChainName'] new_data = [{k:v for k,v in low_dict.items() if k in to_keep} for low_dict in data['data']['items']] # where item is dictionary at lowest level escalations = [{v 'Name':k[v]['name']} for k in data['data']['items'] for v in k if type(k[v])==dict] # merge both lists of python dictionaries to produce flattened list of dictionaries new_data = [{**new,**escl} for new,escl in zip(new_data,escalations)]或者(并且由于您的推薦
json包)如果您已將回應保存為.json檔案:import json with open('response.json', 'r') as handl: data = json.load(handl) to_keep = ['id', 'name', 'priority', 'levelStr', 'escalatingChainId', 'escalatingChainName'] new_data = [{k:v for k,v in low_dict.items() if k in to_keep} for low_dict in data['data']['items']] escalations = [{v 'Name':k[v]['name']} for k in data['data']['items'] for v in k if type(k[v])==dict] new_data = [{**new,**escl} for new,escl in zip(new_data,escalations)]
兩者都產生輸出:
[{'id': 11,
'name': 'BBC',
'priority': 4,
'levelStr': 'All',
'escalatingChainId': 3,
'escalatingChainName': 'Example123'},
{'id': 21,
'name': 'CNBC',
'priority': 4,
'levelStr': 'All',
'escalatingChainId': 3,
'escalatingChainName': 'Example456'}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/453484.html
