我想使用 JSON 数据在 Python 中发出 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}]
关于python - Python 中使用 JSON 数据的 HTTP PUT 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52510584/