方法一
使用dict.get()
if __name__ == '__main__':
import json
employee = '{"id":"000", "name": "111", "department":"222"}'
employee_dict = json.loads(employee)
print(employee_dict.get('dont exist')) # None
print(employee_dict.get('dont exist', '不存在')) # 不存在
方法二
使用try
包裹,例
if __name__ == '__main__':
import json
employee = '{"id":"000", "name": "111", "department":"222"}'
employee_dict = json.loads(employee)
try:
others = employee_dict['other']
except Exception as e:
others = 'dont exist'
print(others)