API 在浏览器上返回 json,但在 python 上解析它时出现此异常:无法解码 JSON 对象
。我使用了 json.load()
和 json.loads()
但失败了。
这是代码。
def handler_timeout(self):
try:
data = json.load(
urlopen(
'https://www.zebapi.com/api/v1/market/ticker/btc/inr'
)
)
buy_price = data['buy']
sell_price = data['sell']
status_message = "Buy: ₹ " + "{:,}".format(buy_price) + " Sell: ₹ " + "{:,}".format(sell_price)
self.ind.set_label(status_message, "")
except Exception, e:
print str(e)
self.ind.set_label("!", "")
return True
这是 urlopen(URL)
的输出:
<addinfourl at 140336849031752 whose fp = <socket._fileobject object at 0x7fa2bb6f1cd0>>
这是 urlopen(URL).read()
的输出:
��`I�%&/m�{J�J��t�`$ؐ@�������iG#)�*��eVe]f@�흼��{����{����;�N'���?\fdl��J�ɞ!���?~|?"~�o���G��~��=J�vv��;#�x���}��e���?=�N�u�/�h��ًWɧ�U�^���Ã���;���}�'���Q��ct
最佳答案
网址内容为gzip
-encoded .
>>> u = urllib.urlopen('https://www.zebapi.com/api/v1/market/ticker/btc/inr')
>>> info = u.info()
>>> info['Content-Encoding']
'gzip'
解压内容。
import gzip
import io
import json
import urllib
u = urllib.urlopen('https://www.zebapi.com/api/v1/market/ticker/btc/inr')
with io.BytesIO(u.read()) as f:
gz = gzip.GzipFile(fileobj=f)
print json.load(gz)
或使用requests
which decode gzip automatically :
import requests
print requests.get('https://www.zebapi.com/api/v1/market/ticker/btc/inr').json()
关于python - 获取 json URL 的 "No JSON object could be decoded",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47647491/