2016-01-21 28 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

相關問題