python json转储不从text/html转换

标签 python json

有人可以解释一下为什么它没有从 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/

相关文章:

python - 在至少 7 天内连续三天登录该产品的用户

javascript - 当响应不在数组中时,在 javascript 中解析 JSON 结果

json - 如何删除部分 JSON Web 响应?

Android ListView 添加了两次项目

python - 有没有办法将动态 url_prefix 添加到 Flask 应用程序中的所有路由?

python - Python 中的授权 REST 服务

python - multiprocessing中map与Pool结合使用时如何划分数据?

python将字符串转换为参数列表

json - 什么是 JSON,它的用途是什么?

ios - 如何使用 NSDictionary 收集嵌套在数组中的 JSON 数据