python json转储不从text/html转换 [英] python json dumps not converting from text/html

查看:200
本文介绍了python json转储不从text/html转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一下为什么它不能从text转换为json以及我需要做些什么以及如何完成它.

Can somebody please explain why its not converting to json from text and what I require to get that done and how to get it accomplished.

>>> 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'
>>>

更新:

使用标头接受为application/json导致我无法解码JSON对象.请帮忙.

With the header accept as application/json lead me to No JSON object could be decoded. Please help..

>>> 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:

You are only stating that the content type of your request is application/json. You can try requesting json using an accept-header:

headers["Accept"] = "application/json"

,但是如果服务器忽略标题,它将无法为您提供帮助.

but if the server ignores the header it won't help you.

此外,响应内容实际上可能是json,因此r.json()可能有效,并且仅是内容类型标头具有误导性.

Also it is possible that the response content actually is json, so r.json() might work, and it's only the content-type header that is misleading.

这篇关于python json转储不从text/html转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆