我正在编写脚本以对Meraki API进行API调用,并且需要将某些值写入CSV文件。给定了所附的屏幕截图,我已经能够从列表中选择某些信息,但与“ timeSeries”无关,因为它似乎是一个不同的小节。
latency_measure = json.loads(session.get('https://api.meraki.com/api/v0/organizations/' + ORG_ID + '/uplinksLossAndLatency', headers=headers).text)
def latency_measure_info(latency_measure):
csv_file1 = open(name + ' appliances -' + str(today) + '.csv', 'w', encoding='utf-8')
fieldnames = ['Network', 'Serial', 'Uplink', 'Destination IP', 'Test 1 Date/Time', 'Test 1 Loss Percent', 'Test 1 Latency', 'Test 2 Date/Time', 'Test 2 Loss Percent', 'Test 2 Latency', 'Test 3 Date/Time', 'Test 3 Loss Percent', 'Test 3 Latency', 'Test 4 Date/Time', 'Test 4 Loss Percent', 'Test 4 Latency']
writer = csv.DictWriter(csv_file1, fieldnames=fieldnames, restval='')
writer.writeheader()
for latency in latency_measure:
if (network_id in network_id_list):
network_name = get_network_name(latency['networkId'], networks)
writer.writerow({'Network': network_name, 'Serial': latency['serial'], 'Uplink': latency['uplink'], 'Destination IP': latency['ip'], 'Test 1 Loss Percent': latency['timeSeries'['lossPercent']], 'Test 1 Latency': latency['latencyMs'], 'Test 2 Date/Time': latency['ts'], 'Test 2 Loss Percent': latency['lossPercent'], 'Test 2 Latency': latency['latencyMs'], 'Test 3 Date/Time': latency['ts'], 'Test 3 Loss Percent': latency['lossPercent'], 'Test 3 Latency': latency['latencyMs'], 'Test 4 Date/Time': latency['ts'], 'Test 4 Loss Percent': latency['lossPercent'], 'Test 4 Latency': latency['latencyMS']})
csv_file1.close()
在将行写入CSV文件时,我可以选择网络,串行,上行链路和目标IP数据,但是一旦进入timeSeries,它就不会提取该信息,因为我不知道如何指定它。
答案 0 :(得分:1)
执行json.loads(..)
后,“ timeSeries”将是list
个dict
中的一个。
print(type(latency["timeSeries"]))
# <class 'list'>
print(type(latency["timeSeries"][0]))
# <class 'dict'>
print(type(latency["timeSeries"][1]))
# <class 'dict'>
...
您首先按索引访问list
的每个元素,然后使用键访问dict
的键值对。
latency["timeSeries"][0]["ts"]
latency["timeSeries"][0]["lossPercent"]
latency["timeSeries"][0]["latencyMs"]
# OR
timeSeries0 = latency["timeSeries"][0]
timeSeries0["ts"]
timeSeries0["lossPercent"]
timeSeries0["latencyMs"]
如果您事先知道索引数量为[0]
,[1]
..,则可以一对一地对其进行硬编码,也可以循环播放timeSeries的所有元素列出并构建您要编写的字典值。