我正在通过返回 JSON 的 Web 调用构建点要素类。 JSON 有点粗略,因为有时记录中不存在键。一旦我有了一个有效的 JSON 对象,我就会尝试这样做:
#requests stuff above this
for i in jsonObj:
try:
if i['properties']['country']:
country = i['properties']['country']
else:
country = 'UNK'
print('Country name not found, using {}'.format(country))
except KeyError, e:
print('Key error: reason: {}'.format(str(e)))
pass
#then do all the arcpy FC creation stuff
结果是一大堆带有“原因:‘国家’”的关键错误,而不是使用通用的‘国家’值‘UNK’来构建这些行,它会简单地忽略它们并构建要素类,留下出那些点。
我已取出 try 并将其保留为条件检查,但它在缺少“国家/地区”键的第一行失败。
总而言之,我只是想检查一个键值对是否存在;如果不是,则将 'UNK' 的通用值分配给 country 变量。
问题的一部分似乎是 if i['properties']['countries'] 正在检查一个值,而不是 key 本身是否存在?如何更有效地检查 key 是否存在?
我已阅读 Check if a given key already exists in a dictionary并将我的代码修改为这两个,但都没有产生预期的结果:
for i in jsonObj:
try:
# get coordinates first
if i['geometry']['coordinates']:
ycoord = float(i['geometry']['coordinates'][1])
xcoord = float(i['geometry']['coordinates'][0])
if i['properties']['city'] in i:
city = i['properties']['city']
else:
city = 'UNK'
if i['properties']['country'] in i:
country = i['properties']['country']
else:
country = 'UNK'
和
for i in jsonObj:
try:
# get coordinates first
if i['geometry']['coordinates']:
ycoord = float(i['geometry']['coordinates'][1])
xcoord = float(i['geometry']['coordinates'][0])
if 'city' in i:
city = i['properties']['city']
else:
city = 'UNK'
if 'country' in i:
country = i['properties']['country']
else:
country = 'UNK'
我确实在每条记录/词典中都有“属性”键,但不能保证我是否有“国家”键。 json 响应中有些行有它,有些行没有
请您参考如下方法:
你最后一次尝试:
if 'country' in i:
country = i['properties']['country']
else:
country = 'UNK'
很接近,但是你正在管理一个字典的字典,并且 'country' 更有可能成为子字典的键,所以修复是:
if 'country' in i['properties']:
country = i['properties']['country']
else:
country = 'UNK'
或者更好更短地使用带有默认值的 get(我建议最后一个超过 quickfix):
country = i['properties'].get('country','UNK')
