簡體   English   中英

如何從嵌套的 JSON 文件中提取 JSON?

[英]How to extract JSON from a nested JSON file?

我打電話給 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,如下所示,其中escalatingChainNameescalatingChain列表中的name ,以便我可以將其寫入 CSV 文件。

{
    "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 function 可用於僅將必要的鍵值或嵌套鍵值復制到新的 JSON object?

使用以下代碼,我可以獲得詳細信息列表。

json_response = response.json()
items = json_response['data']
details = items['items']

我可以使用打印單個列表項

for x in details:
    print(x)

我如何從這里提取必要的字段,如 id、名稱、優先級和來自escalatingchain的名稱以創建新列表或 JSON?

你可以試試:

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

解決這個問題的兩種方法取決於您是使用 python 列表和字典理解處理變量還是.json文件:

  1. 其中已經定義了字典類型(嵌套)的數據變量:

     # 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)]
  2. 或者(由於您參考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)]

兩者都產生 output:

[{'id': 11,
  'name': 'BBC',
  'priority': 4,
  'levelStr': 'All',
  'escalatingChainId': 3,
  'escalatingChainName': 'Example123'},
 {'id': 21,
  'name': 'CNBC',
  'priority': 4,
  'levelStr': 'All',
  'escalatingChainId': 3,
  'escalatingChainName': 'Example456'}]

沒有現有的 function 可以滿足您的需求,因此您需要編寫一個。 幸運的是,在這種情況下這並不太難 — 基本上,您只需通過從現有數據中提取所需的數據片段來創建新項目列表。

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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM