【问题标题】:No JSON object could be decoded when opening stackexchange api as json以 json 形式打开 stackexchange api 时无法解码任何 JSON 对象
【发布时间】:2013-05-14 22:08:40
【问题描述】:

我正在访问 JSON 文件的特定 URL(来自 stackexchange 和 stackoverflow api)。执行json.loads() 命令时显示以下错误:

import urllib2
import json

url = "http://api.stackexchange.com/2.1/tags?order=desc&sort=popular&site=quant&pagesize=100&page=1"    
data = json.loads(urllib2.urlopen(url).read())

<ipython-input-20-7540e91a8ff2> in <module>()
----> 1 data = json.loads(urllib2.urlopen(url).read())

/usr/lib/python2.7/json/__init__.pyc in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    336             parse_int is None and parse_float is None and
    337             parse_constant is None and object_pairs_hook is None and not kw):
--> 338         return _default_decoder.decode(s)
    339     if cls is None:
    340         cls = JSONDecoder

/usr/lib/python2.7/json/decoder.pyc in decode(self, s, _w)
    363 
    364         """
--> 365         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    366         end = _w(s, end).end()
    367         if end != len(s):

/usr/lib/python2.7/json/decoder.pyc in raw_decode(self, s, idx)
    381             obj, end = self.scan_once(s, idx)
    382         except StopIteration:
--> 383             raise ValueError("No JSON object could be decoded")
    384         return obj, end

ValueError: No JSON object could be decoded

另一方面,twitter api 一切正常...为什么?

【问题讨论】:

    标签: python json stackexchange


    【解决方案1】:

    正如@Thomas 所说,这是因为the gzip compression。
    我建议使用 requests 库,它会为你担心这种事情:

    import requests
    
    data_url = "https://api.stackexchange.com/2.1/search?page=1&pagesize=10&order=desc&sort=activity&tagged=pandas&site=stackoverflow"
    data_json = requests.get(data_url).json()
    

    【讨论】:

      【解决方案2】:

      StackExchange API always compresses its responses,但 Python doesn't automatically uncompress it,因此 json 正在获取 gzip 压缩数据。

      This answer 展示了如何使用 gzip 模块来处理响应。

      【讨论】:

      • 很高兴它有帮助。如果这解决了您的问题,请不要忘记接受答案(单击左侧的勾号)。
      猜你喜欢
      • 2019-04-26
      • 2013-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-26
      • 2015-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多