Python的JSON模块:通过字典访问抑制异常

2024-04-20 00:40:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我注意到,如果我想访问一个JSON文档中不存在的键,会出现一个突发异常。 这个例外的问题是,我在文件里找不到太多关于它的东西。 第二个问题是,我没有找到函数来进行检查,不管项目是否存在。 第三件事是,在这种情况下不需要例外。返回NULL会更好。 这是一些示例代码。是否有人知道一种esay方法来禁止抛出异常或忽略它?你知道吗

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)

Tags: ofthecomsendmodelifistype
1条回答
网友
1楼 · 发布于 2024-04-20 00:40:35

一旦解析了JSON文档,它就是一个Python数据结构。从那时起,所有关于如何使用python列表或字典的常规规则都适用。尝试访问不存在的词典中的键将引发KeyError,除非您使用^{}(并且可能提供除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 ^{}):

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

相关问题 更多 >