我有来自openWeather的JSON格式的数据,它给出了错误
Traceback (most recent call last):
File "testjson.py", line 7, in <module>
data = json.load(data_file)
File "E:\Program Files\Python27\lib\json\__init__.py", line 290, in load
**kw)
File "E:\Program Files\Python27\lib\json\__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "E:\Program Files\Python27\lib\json\decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "E:\Program Files\Python27\lib\json\decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
我已通过JSONlint运行JSON数据,并且没问题。这是它
{"city":{"id":7839581,"name":"Gold Coast","coord":{"lon":153.36055,"lat":-27.97851},"country":"AU","population":0,"sys":{"population":0}},"cod":"200","message":0.0184,"cnt":40,"list":[{"dt":1488844800,"main":{"temp":297.46,"temp_min":297.12,"temp_max":297.46,"pressure":1019.12,"sea_level":1025.73,"grnd_level":1019.12,"humidity":100,"temp_kf":0.34},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"clouds":{"all":0},"wind":{"speed":5.16,"deg":203.005},"rain":{}}]}
最后是我的Python代码
import json
from pprint import pprint
with open('weather.json') as data_file:
data = json.load(data_file)
pprint(data)
我已经搞乱了几个小时,在这里以及搜索带给我的任何其他地方追逐潜在客户。与许多更微妙的错误不同,这似乎只是拒绝了整个,我不知道为什么
有人可以对此有所了解吗?
答案 0 :(得分:1)
您需要先从文件中读取数据,然后使用json
模块加载它,如下例所示:
import json
with open("weather.json", 'r') as f:
# read the data
data = f.read()
# then load it using json.loads()
final = json.loads(data)
print(final['city'])
输出:
{u'name': u'Gold Coast', u'country': u'AU', u'coord': {u'lat': -27.97851, u'lon': 153.36055}, u'sys': {u'population': 0}, u'id': 7839581, u'population': 0}
修改强>
您还可以使用json.load()
来完成此任务,如下例所示:
import json
with open("weather.json", 'r') as f:
final = json.load(f)
print(final['city'])
输出:
{u'name': u'Gold Coast', u'country': u'AU', u'coord': {u'lat': -27.97851, u'lon': 153.36055}, u'sys': {u'population': 0}, u'id': 7839581, u'population': 0}
为什么这样做会这样?这很简单,您可以查看文档json.load()输入必须具有read()
方法:
反序列化fp(.read() - 支持包含文件的文件对象 JSON文档)使用此转换表的Python对象。
否则在json.loads()
内,输入必须是str
或unicode instance
:
反序列化s(包含JSON文档的str或unicode实例) 使用此转换表的Python对象。
PS:如果两种方法都失败了,您应该查看一下您的文件并检查它是否包含有效的JSON。
答案 1 :(得分:0)