我正在從返回JSON的Web調用構建點要素類。 JSON有點簡單,有時鍵不存在於記錄中。我試圖做到這一點,一旦我有一個有效的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響應中的某些行有它,有些行不
你可以嘗試'如果'屬性'在我:,而不是'如果'國家'在我:'。 –
你在每本字典中都有「屬性」鍵嗎? –
是的,我在每個記錄/字典中都有'屬性'鍵,但我是否擁有'國家/地區'鍵是不能保證的。 json響應中的某些行有它,有些行不。 – auslander