【发布时间】:2017-03-05 09:24:00
【问题描述】:
我正在通过返回 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'] 正在检查一个值,而不是密钥本身的存在?如何更有效地检查密钥是否存在?
我已阅读 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 'properties' in i:, notif 'country' in i:`。 -
每个字典中都有
properties键吗? -
是的,我在每条记录/字典中都有'properties'键,但不能保证我是否有'country'键。 json 响应中的某些行有它,有些行没有。