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

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)


blh*_*ing 5

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)

  • @dumbledad 为什么不呢?它是在 OP 问题中发布的“headers”字典中定义的。 (2认同)