问:如何从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+网络列表中的两个。
我想要做的是:
查找状态"failed",并打印连接错误,并在以下位置找到它:
'networkId: XYZ',‘网络名称: ABC',’接口:wan1 1‘,'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的文章,但这都是关于dicts和lists的,对我来说,帮助我解决我的具体问题没有多大意义。
任何帮助都是非常感谢的。
发布于 2021-10-28 11:58:01
试试这个:
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"],
)https://stackoverflow.com/questions/69753538
复制相似问题