【问题标题】:My simple REST call to openweathermap not working - Error: No JSON object could be decoded我对 openweathermap 的简单 REST 调用不起作用 - 错误:无法解码 JSON 对象
【发布时间】:2016-01-21 19:48:33
【问题描述】:

我的代码很简单。当我运行下面的代码时,当我将url 直接粘贴到浏览器中时,我应该得到一个 JSON,但是当我尝试使用 Python 时,我得到了错误

ValueError: 无法解码 JSON 对象

import urllib2
import json

url = 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=2de143494c0b295cca9337e1e96b00e0'

json_obj = urllib2.urlopen(url)
data = json.load(json_obj) #THIS IS LINE 7, i.e. where the error occurs

这是我得到的完整错误:

Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Python27\lib\json\__init__.py", line 291, in load
  **kw)
File "C:\Python27\lib\json\__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "C:\Python27\lib\json\decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python27\lib\json\decoder.py", line 382, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

【问题讨论】:

    标签: python json rest urllib2 openweathermap


    【解决方案1】:

    尝试使用requests 代替 urllib。

    `# -*- coding: utf-8 -*-
    
    import requests
    
    url = 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=2de143494c0b295cca9337e1e96b00e0'
    
    r = requests.get(url)
    print r.status_code
    print r.json()
    >>> {u'clouds': {u'all': 0}, u'name': u'London', u'coord': {u'lat': 51.51, u'lon': -0.13}, u'sys': {u'country': u'GB', u'sunset': 1453393861, u'message': 0.0089, u'type': 1, u'id': 509
    1, u'sunrise': 1453362798}, u'weather': [{u'main': u'Clear', u'id': 800, u'icon': u'01n', u'description': u'Sky is Clear'}], u'cod': 200, u'base': u'cmc stations', u'dt': 145340535
    4, u'main': {u'pressure': 1022, u'temp_min': 276.85, u'temp_max': 279.15, u'temp': 277.76, u'humidity': 70}, u'id': 2643743, u'wind': {u'speed': 3.6, u'deg': 150}}
    

    来自请求documentation

    如果 JSON 解码失败,r.json 会引发异常。为了 例如,如果响应得到 204(无内容),或者如果响应 包含无效 JSON,尝试 r.json 引发 ValueError: No JSON object could be decoded

    因此,请检查您返回 r.status_code 的状态代码类型,根据您的第二条评论,存在 UTF 问题。

    【讨论】:

    • 我完全尝试了您粘贴的内容,但仍然收到 JSONDecodeError。这可能是因为我在 Windows 上吗? imgur.com/a04Uv6W
    • @user1406716 嗯,也许(不确定),我在 Linux 上
    • @user1406716 r.text 返回什么?
    • @user1406716 添加# -*- coding: utf-8 -*- 作为脚本的第一行
    猜你喜欢
    • 2016-07-21
    • 2015-03-29
    • 2018-08-14
    • 2023-03-12
    • 2012-04-15
    • 2016-11-05
    • 2014-06-21
    • 2011-09-17
    • 2019-01-21
    相关资源
    最近更新 更多