有人可以解释一下为什么它没有从 text
转换为 json
以及我需要什么来完成它以及如何完成它。
>>> import json
>>> import requests
>>> url = 'http://localhost:8000/some/endpoint'
>>> payload = {'some': 'data'}
>>> headers = {'content-type': 'application/json'}
>>> r = requests.post(url, data=json.dumps(payload), headers=headers)
>>> r.headers.get('content-type')
'text/html'
>>>
更新:
使用 header Accept as application/json 导致我无法解码任何 JSON 对象。请帮忙..
>>> import json
>>> import requests
>>> url = 'http://localhost:8000/some/endpoint'
>>> payload = {'some': 'data'}
>>> headers = {'content-type': 'application/json','accept':'application/json'}
>>> r = requests.post(url, data=json.dumps(payload), headers=headers)
>>> r.headers
CaseInsensitiveDict({'date': 'Thu, 13 Jun 2013 01:43:16 GMT', 'content-type': 'text/html', 'server': 'WSGIServer/0.1 Python/2.7.3'})
>>> r.json()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/requests-1.2.3-py2.7.egg/requests/models.py", line 651, in json
return json.loads(self.text or self.content, **kwargs)
File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
>>>
最佳答案
您只是声明您的请求的内容类型是 application/json
。您可以尝试使用 accept-header 请求 json :
headers["Accept"] = "application/json"
但是如果服务器忽略了 header ,它就不会帮助你。
此外,响应内容实际上可能是 json,因此 r.json()
可能有效,并且只有内容类型 header 具有误导性。
关于python json转储不从text/html转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17069303/