[英]How to grab value in data from json resonse?
問:如何從我的 api 響應中獲取值?
我的代碼:
#!/usr/bin/python3
API_KEY = ""
ORG_ID = ""
import meraki
import requests
import json
import time
import sys
from pprint import pprint
url = "https://api.meraki.com/api/v1/organizations/""/appliance/uplink/statuses"
payload = {}
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-Cisco-Meraki-API-Key': (API_KEY)
}
response = requests.request('GET', url, headers=headers, data = payload)
pprint(response.json())
響應:
{'networkId': 'A_1234567890',
'serial': 'abcd-1234-abcd',
'model': 'MXYZ',
'lastReportedAt': '2021-01-01T00:00:00Z',
'uplinks': [{'interface': 'wan1',
'status': 'active',
'ip': 'x.x.x.x',
'gateway': 'x.x.x.x',
'publicIp': 'x.x.x.x',
'primaryDns': 'x.x.x.x',
'secondaryDns': 'x.x.x.x',
'ipAssignedBy': 'dhcp'},
{'interface': 'wan2',
'status': 'ready',
'ip': 'x.x.x.x',
'gateway': 'x.x.x.x',
'publicIp': 'x.x.x.x',
'primaryDns': 'x.x.x.x',
'secondaryDns': 'x.x.x.x',
'ipAssignedBy': 'dhcp'}]},
{'networkId': 'B_0987654321',
'serial': '1234-abcd-1234',
'model': 'MXYZ',
'lastReportedAt': '2021-01-01T00:00:00Z',
'uplinks': [{'interface': 'wan1',
'status': 'active',
'ip': 'x.x.x.x',
'gateway': 'x.x.x.x',
'publicIp': 'x.x.x.x',
'primaryDns': 'x.x.x.x',
'secondaryDns': 'x.x.x.x',
'ipAssignedBy': 'dhcp'},
{'interface': 'wan2',
'status': 'failed',
'ip': 'x.x.x.x',
'gateway': 'x.x.x.x',
'publicIp': 'x.x.x.x',
'primaryDns': 'x.x.x.x',
'secondaryDns': 'x.x.x.x',
'ipAssignedBy': 'dhcp'}]},
這些是 50 多個網絡的整個列表中的 2 個。
我想要它做的是:
找到狀態“失敗”,並打印連接錯誤,以及在哪里可以找到它,如下所示:
['networkId: XYZ', 'network name: ABC', 'interface: wan1', 'uplinks: failed'] 或類似這些內容以使其可讀。
此外,我已經獲得了這段代碼,可以從 networkId 創建一個網絡名稱並搜索上行鏈路,但我無法使其工作。
net_names = {
'A_1234567890':'Amsterdam',
'B_0987654321':'Rotterdam'
}
network_id = response_json.get('networkId')
for item in response_json['uplinks']:
if item['status'] == "active":
print('network ID:', network_id,'network_name:',net_names.get(network_id), 'Interface:',item['interface'])
我對 Python 還是很陌生,我閱讀了很多關於 JSON 的內容,但它全都在字典和列表上,對我來說沒有多大意義,可以幫助我解決我的具體問題。
任何幫助是極大的贊賞。
嘗試這個:
json_data = response.json()
net_names = {"A_1234567890": "Amsterdam", "B_0987654321": "Rotterdam"}
for network_data in json_data:
network_id = network_data.get("networkId")
for uplink_data in network_data.get("uplinks", []):
if uplink_data["status"] == "active":
print(
"network ID:",
network_id,
"network_name:",
net_names.get(network_id, "n/a"),
"Interface:",
uplink_data["interface"],
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.