2016-01-21 32 views
0

我的代码非常简单。当我运行下面的代码,我应该得到一个JSON回来,因为我可以看到当我直接粘贴url在浏览器中,但是当我尝试使用Python,我得到的错误我的简单REST调用openweathermap不工作 - 错误:没有JSON对象可以解码

ValueError: No JSON object could be decoded

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 

回答

0

尝试使用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

In case the JSON decoding fails, r.json raises an exception. For example, if the response gets a 204 (No Content), or if the response contains invalid JSON, attempting r.json raises ValueError: No JSON object could be decoded .

因此,检查你得到什么样的状态代码回来r.status_code并根据您的第二个评论有一个UTF问题。

+0

我尝试了你粘贴的东西,仍然得到'JSONDecodeError'。这可能是因为我在Windows上吗? http://imgur.com/a04Uv6W – user1406716

+0

@ user1406716 hm,也许(不知道这个),我在Linux上 – dm295

+0

@ user1406716'r.text'返回什么? – dm295

相关问题