JSON中带前导零的字符串?

时间:2017-08-09 19:27:50

标签: python json

我有一个Python脚本,它使用请求模块将JSON发布到API。但是,我发布了一个使用十六进制的哈希。我使用以下代码时遇到错误:

r = requests.post('apiurl.com/do/stuff', json={"key": '0052ccca'})

响应是400错误:

{"message": "Could not parse request body into json: Unrecognized token 
\'k0052ccca\': was expecting (\'true\', \'false\' or \'null\')\n at 
[Source: [B@410c3139; line: 2, column: 23]"}

this answer中,建议将前导零视为字符串,但我已经这样做了,但仍然出错。

1 个答案:

答案 0 :(得分:4)

>>> import requests
>>> response = requests.post('http://httpbin.org/post', json={"key": '0052ccca'})
>>> print(response.text)
{
  "args": {}, 
  "data": "{\"key\": \"0052ccca\"}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Content-Length": "19", 
    "Content-Type": "application/json", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.3"
  }, 
  "json": {
    "key": "0052ccca"
  }, 
  "origin": "38.98.147.133", 
  "url": "http://httpbin.org/post"
}

解码json没有任何问题,因为您可以看到它被请求正确编码:

>>> response.request.body
b'{"key": "0052ccca"}'

所以问题是服务器端(或者您的示例代码与您的实际代码有太大不同,以揭示真正的问题)。