我正在尝试使用 python 发布 JSON 数据(RESTful API)。
null = none
payload = {
"priority": 1,
"hello_id": 207,
"bye_id": 207,
"s1": 1,
"s2": 2,
"sub": "CHECK 123",
"t1": "Leave",
"product_id": null,
"due": "2001-01-01T06:11:54.884Z",
"tags": [
"HelloTag"
]
}
headers = {'content-type': 'application/json'}
r = requests.post(myurl, data=json.dumps(payload), headers=headers)
(OR)
r = requests.post(myurl, json = json.dumps(payload_post), headers=headers)
(OR)
r = requests.post(myurl, data = payload_post, headers=headers, auth=(username_accadmin, password_accadmin))
(OR)
r = requests.post(myurl, json=payload, headers=headers)
以上 3 行似乎都没有产生预期的响应(或)我在 Postman 中获得的响应。
In the response I get :
"Validation failed","errors":[{"field":"priority","message":"Unexpected/invalid field in request","code":"invalid_field"}]
(FOR ALL FIELDS IN THE JSON DATA)
为什么我用dumps()方法将dict()转成JSON数据还是不对?
注意:如果负载中的所有字段都是字符串,则数据会按预期发布。
最佳答案
data
应该是 dict
或 list
,而不是字符串(dumps
)返回。
r = requests.post(myurl, json=payload, headers=headers)
参见 documentation .此外,您应该在负载中使用 None
而不是 null
。
关于python - 请求正文具有无效的 json 格式 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45350227/