我正在通过返回 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 是否存在?
我已阅读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
更好更短(我建议使用快速修复中的最后一个):
country = i['properties'].get('country','UNK')
关于python - 对被忽略的 JSON 键值对的条件检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42588458/