需要在 {} 中插入 JSON 文件内容才能获得有效负载。无法成功执行此操作。有什么想法吗?
尝试将 JSON 文件内容写入字符串,但失败。尝试将 JSON 文件插入有效负载 = {},失败。
import requests, meraki, json, os, sys
with open('networkid.txt') as file:
array = file.readlines()
for line in array:
line = line.rstrip("n")
url = 'https://api.meraki.com/api/v0/networks/%s/alertSettings' %line
payload = {}
headers = { 'X-Cisco-Meraki-API-Key': 'API Key','Content-Type': 'application/json'}
response = requests.request('PUT', url, headers = headers, data = payload, allow_redirects=True, timeout = 10)
print(response.text)
我正在编写一个脚本,通过 API 将参数部署到 Meraki 网络。我在其自己的文件中正确格式化了 JSON 信息,我需要的是将 JSON 数据插入脚本中有效负载的位置。关于如何做到这一点的任何想法?我已经有一个 for 循环,这是运行.txt文件中包含的网络 ID 列表所必需的。有什么想法吗?
requests.request
中的 data
参数需要 (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:Request
。
您可以使用 json.load 将正确格式的 json 文件转换为 python 字典:
with open('json_information.json') as f:
payload = json.load(f)
然后可以直接将data=payload
传递到调用中requests.request
:
with open('networkid.txt') as file:
array = file.readlines()
for line in array:
line = line.rstrip("n")
url = 'https://api.meraki.com/api/v0/networks/%s/alertSettings' % line
headers = { 'X-Cisco-Meraki-API-Key': 'API Key','Content-Type': 'application/json'}
response = requests.request('PUT',
url,
headers=headers,
data=payload,
timeout = 10) # allow_redirects is True by default
print(response.text)