使用Python读取JSON文件时,搜索指定关键字‘center’Python会报KeyError的错,但JSON文件中确实有‘center’关键词。
这是Python的代码
import json
# 探索数据的结构
filename = 'data/中华人民共和国.json'
with open(filename,encoding='utf-8') as f:
all_eq_data = json.load(f)
# 以易读的方式存储
# readable_file = 'data/1中华人民共和国.json'
# with open(readable_file, 'w', encoding='utf-8') as f:
# json.dump(all_eq_data, f, indent=4)# 接受一个JSON数据对象和一个文件对象,并将数据写入这个文件中,indent=4让数据结构匹配缩进量来设置数据的格式
# 提取地区的数量
all_eq_dicts = all_eq_data['features']
# 提取邮政编码和位置信息
adcodes, names, lons, lats = [], [], [], []
for eq_dict in all_eq_dicts:
adcode = eq_dict['properties']['adcode']
name = eq_dict['properties']['name']
lon = eq_dict['properties']['center'][0]
lat = eq_dict['properties']['center'][1]
adcodes.append(adcode)
names.append(name)
lons.append(lon)
lats.append(lat)
print(adcodes)
print(names)
print(lons)
print(lats)
这是对应的JSON文件,只截取了一部分
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"adcode": 110000,
"name": "\u5317\u4eac\u5e02",
"center": [
116.405285,
39.904989
],
"centroid": [
116.41995,
40.18994
],
"childrenNum": 16,
"level": "province",
"parent": {
"adcode": 100000
},
"subFeatureIndex": 0,
"acroutes": [
100000
]
}
}
}
这是报的错
Traceback (most recent call last):
File "D:\Python\Py project\py_Learn\JSON\1eq_explore.py", line 21, in <module>
lon = eq_dict['properties']['center'][0]
KeyError: 'center'
希望有方法可以正常读取到数据