【问题标题】:Python Requests: requests.get(url).json() ErrorPython 请求:requests.get(url).json() 错误
【发布时间】:2019-04-01 21:06:43
【问题描述】:

当我尝试使用 python 请求时,我得到以下信息:当我尝试确保请求是 json 格式时。使用requests.get(url)时的请求是<Response [200]>

但是,当使用request.get(url).json() 时,我得到以下信息:

  File "/usr/local/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/local/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

打印requests.get(url).headers 给出以下信息:

{'Server': 'nginx/1.10.3 (Ubuntu)', 'Date': 'Mon, 01 Apr 2019 21:03:28 GMT', 'Content-Type': 'text/html', 'Last-Modified': 'Mon, 25 Mar 2019 21:25:01 GMT', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'ETag': 'W/"5c99472d-806"', 'Strict-Transport-Security': 'max-age=63072000; includeSubdomains', 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff', 'Content-Encoding': 'gzip'}

我试过剪掉某些字符,例如 、\、\0,但这并不影响结果。

【问题讨论】:

  • 您的响应中的服务器标头显示内容类型是text/html,而不是application/json。您可以使用.content 属性查看正文包含的内容。
  • 是的,如何才能将其更改为 application/json?
  • 您的 JSON 似乎在使用单引号,请尝试将内容类型更改为 application/json,将页眉设置为:Content-Type,将您的页面提供给 application/json
  • @PrestonHager 这不是 json,这是代表响应标头的请求的字典。
  • 如何更改内容类型?

标签: python json flask python-requests


【解决方案1】:

下面的请求应该可以工作。

import requests requests.get(URL, headers={'content-type':'application/json'}).json()

【讨论】:

  • 你也可以使用 json.loads() 来响应。
  • 这给出了相同的最终结果:文件“/usr/lib/python3.5/json/__init__.py”,第 319 行,加载返回 _default_decoder.decode(s) 文件“/usr/ lib/python3.5/json/decoder.py”,第 339 行,在 decode obj 中,end = self.raw_decode(s, idx=_w(s, 0).end()) 文件“/usr/lib/python3. 5/json/decoder.py",第 357 行,在 raw_decode 中引发 JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
  • 即使在我的 request.get 参数中添加 headers={'accept': 'application/json'} 后,我仍然可以看到我的原始内容类型是 'test/html'。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-24
  • 1970-01-01
  • 2015-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多