如何将JSON数据插入到Payload中以进行API部署?

时间:2019-01-09 16:29:10

标签: python json api

需要在{}内插入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数据插入脚本中Payload的位置。有关如何执行此操作的任何想法?我已经有一个for循环,它是运行.txt文件中包含的网络ID列表所必需的。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

data中的requests.request参数采用(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)