2014-09-21 57 views
-1

我注意到,如果我想訪問不存在的JSON文檔中的關鍵字,會突然發生異常。 這個例外的問題是,我沒有在文件中找到很多關於它的問題。 第二個問題是,我沒有找到功能進行檢查,無論項目是否存在。 第三件事是,在這種情況下的例外是沒有必要的。返回NULL會更好。 這是一些示例代碼。是否有人知道一種平抑的方法來抑制拋出異常或忽略它?Python的JSON模塊:通過字典訪問來抑制異常

def make_command(p): 
    type = p['t'] 

    # remote control is about controlling the model (thrust and attitude) 
    if type == 'rc': 
    com = "%d,%d,%d,%d" % (p['r'], p['p'], p['f'], p['y']) 
    send_command("RC#", com) 

    # Add a waypoint 
    if type == 'uav': 
    com = "%d,%d,%d,%d" % (p['lat_d'], p['lon_d'], p['alt_m'], p['flag_t']) 
    send_command("UAV#", com) 

    # PID config is about to change the sensitivity of the model to changes in attitude 
    if type == 'pid': 
    com = "%.2f,%.2f,%.4f,%.2f;%.2f,%.2f,%.4f,%.2f;%.2f,%.2f,%.4f,%.2f;%.2f,%.2f,%.4f,%.2f;%.2f,%.2f,%.4f,%.2f;%.2f,%.2f,%.2f,%.2f,%.2f" % (
     p['p_rkp'], p['p_rki'], p['p_rkd'], p['p_rimax'], 
     p['r_rkp'], p['r_rki'], p['r_rkd'], p['r_rimax'], 
     p['y_rkp'], p['y_rki'], p['y_rkd'], p['y_rimax'], 
     p['t_rkp'], p['t_rki'], p['t_rkd'], p['t_rimax'], 
     p['a_rkp'], p['a_rki'], p['a_rkd'], p['a_rimax'], 
     p['p_skp'], p['r_skp'], p['y_skp'], p['t_skp'], p['a_skp']) 
    send_command("PID#", com) 

    # This section is about correcting drifts while model is flying (e.g. due to imbalances of the model) 
    if type == 'cmp': 
    com = "%.2f,%.2f" % (p['r'], p['p']) 
    send_command("CMP#", com) 

    # With this section you may start the calibration of the gyro again 
    if type == 'gyr': 
    com = "%d" % (p['cal']) 
    send_command("GYR#", com) 

    # User interactant for gyrometer calibration 
    if type == 'user_interactant': 
    ser_write("x") 

    # Ping service for calculating the latency of the connection 
    if type == 'ping': 
    com = '{"t":"pong","v":%d}' % (p['v']) 
    udp_write(com, udp_clients) 
+1

能不能請你改一下你的問題,因此讀起來更像是一個實際的問題,而不是像在胡說八道? – 2014-09-21 16:11:29

+0

我不確定你在問什麼,但這可能有所幫助:https://docs.python.org/2/tutorial/errors.html – jonrsharpe 2014-09-21 16:11:59

+0

不要在問題中添加答案。 – jonrsharpe 2014-09-21 17:12:26

回答

1

一旦你解析了一個JSON文檔,它只是一個Python數據結構。從那裏開始,所有關於如何使用python列表或詞典的常規規則都適用。正嘗試在不存在將引發KeyError,除非你使用dict.get()(也可能提供其它的是None默認值)字典訪問關鍵:先檢查

>>> dct = {'foo': 42} 
>>> dct['bar'] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
KeyError: 'bar' 
>>> 
>>> print dct.get('bar') 
None 
>>> print dct.get('bar', 'NOTFOUND') 
'NOTFOUND' 

爲了如果按鍵在字典中,您只需使用in操作符(見docs for dict):

>>> 'foo' in dct 
True 
>>> 'bar' in dct 
False 
+0

基於我的例子,它將是相對昂貴的,並且有很多代碼來檢查每個密鑰是否存在異常。有沒有辦法解決? – dgrat 2014-09-21 16:17:27

+0

是的,像我演示的那樣,使用'dct.get(key,default)'(爲您的用例使用適當的默認值或標記值)。 – 2014-09-21 16:20:23

+0

這看起來不錯 – dgrat 2014-09-21 16:22:07