【问题标题】:String with leading zeros in JSON?JSON中带有前导零的字符串?
【发布时间】:2018-01-17 20:12:30
【问题描述】:

我有一个 Python 脚本,它使用 requests 模块将 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 中,建议将前导零视为字符串,但我已经这样做了,但仍然出现错误。

【问题讨论】:

    标签: python json


    【解决方案1】:
    >>> 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"}'
    

    所以问题出在服务器端(或者您的示例代码与您的真实代码差异太大,无法揭示真正的问题)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-05
      • 1970-01-01
      • 2020-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-02
      • 2019-07-08
      相关资源
      最近更新 更多