请求体具有无效的json格式 - Python

时间:2017-07-27 12:01:36

标签: python json python-requests

我尝试使用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,数据也会出错?

注意:如果有效负载中的所有字段都是字符串,则数据将按预期发布。

1 个答案:

答案 0 :(得分:3)

data应该是dictlist,而不是字符串(dumps)返回。

r = requests.post(myurl, json=payload, headers=headers)

请参阅documentation。此外,您应在有效负载中使用None而不是null

相关问题