Python 中的 HTTP PUT 请求使用 JSON 数据

HTTP PUT request in Python using JSON data

我想在 Python 中使用 JSON 数据作为

发出 PUT 请求
data = [{"$TestKey": 4},{"$TestKey": 5}]

有什么办法吗?

import requests
import json

url = 'http://localhost:6061/data/'

data = '[{"$key": 8},{"$key": 7}]'

headers = {"Content-Type": "application/json"}

response = requests.put(url, data=json.dumps(data), headers=headers)

res = response.json()

print(res)

收到此错误

requests.exceptions.InvalidHeader: Value for header {data: [{'$key': 4}, {'$key': 5}]} must be of type str or bytes, not <class 'list'>

您的 data 已经是 JSON 格式的字符串。您可以直接将其传递给 requests.put 而不是再次使用 json.dumps 进行转换。

变化:

response = requests.put(url, data=json.dumps(data), headers=headers)

至:

response = requests.put(url, data=data, headers=headers)

或者,您的 data 可以存储数据结构,以便 json.dumps 可以将其转换为 JSON。

变化:

data = '[{"$key": 8},{"$key": 7}]'

至:

data = [{"$key": 8},{"$key": 7}]

requests 库中的 HTTP 方法有一个 json 参数,它将为您执行 json.dumps() 并将 Content-Type header 设置为 application/json:

data = [{"$key": 8},{"$key": 7}]
response = requests.put(url, json=data)