ama*_*r19 6 python json http put
我想使用JSON数据在Python中发出PUT请求
data = [{"$TestKey": 4},{"$TestKey": 5}]
Run Code Online (Sandbox Code Playgroud)
有什么办法吗?
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)
Run Code Online (Sandbox Code Playgroud)
得到这个错误
requests.exceptions.InvalidHeader: Value for header {data: [{'$key': 4}, {'$key': 5}]} must be of type str or bytes, not <class 'list'>
mon*_*kut 10
库中的 HTTP 方法requests
有一个json
参数,当给出该参数时,它将json.dumps()
为您执行并将 Content-Type 标头设置为application/json
:
data = [{"$key": 8},{"$key": 7}]
response = requests.put(url, json=data)
Run Code Online (Sandbox Code Playgroud)
您data
已经是JSON格式的字符串。您可以将其直接传递给,requests.put
而无需json.dumps
再次进行转换。
更改:
response = requests.put(url, data=json.dumps(data), headers=headers)
Run Code Online (Sandbox Code Playgroud)
至:
response = requests.put(url, data=data, headers=headers)
Run Code Online (Sandbox Code Playgroud)
另外,您data
也可以存储数据结构,以便json.dumps
将其转换为JSON。
更改:
data = '[{"$key": 8},{"$key": 7}]'
Run Code Online (Sandbox Code Playgroud)
至:
data = [{"$key": 8},{"$key": 7}]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6654 次 |
最近记录: |