Skip to main content
 首页 » 编程设计

python json 转储不从文本/html 转换

2024年11月01日9yjmyzz

有人可以解释一下为什么它没有从 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 引导我到 No JSON object could be decoded。请帮助..

>>> 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 具有误导性。