python - 读取json格式数据时,不知道是否包含某关键字及其值,怎么办?

查看:456
本文介绍了python - 读取json格式数据时,不知道是否包含某关键字及其值,怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

用python读取json格式的数据

    get_json = json.loads(get_data)
    y1 = get_json['x1']
    y2 = get_json['x2']
    y3 = get_json['x3']

如果有x3,我就需要读出x3。但是我不知道这个json数据里面有没有x3这个数据,如果没有,执行这一步好像就挂掉了。
怎么办?

解决方案

 y1 = get_json['x1'] if 'x1' in get_json else ""
 或者
  y1 = getjson.get('x1', "")
 
 这样判断下
 

get(key[, default ])

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to
None, so that this method never raises a KeyError.

这篇关于python - 读取json格式数据时,不知道是否包含某关键字及其值,怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆