Home  >  Q&A  >  body text

读取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这个数据,如果没有,执行这一步好像就挂掉了。怎么办?

高洛峰高洛峰2900 days ago1053

reply all(4)I'll reply

  • 欧阳克

    欧阳克2016-11-10 16:27:54

     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.


    reply
    0
  • 三叔

    三叔2016-11-10 16:25:46

    还有1种方式是用in,比如"x3" in get_json,但是个人比较喜欢直接用get_json.get("x3"),如果不存在该键值,直接返回的就是1个None。

    reply
    0
  • 欧阳克

    欧阳克2016-11-10 16:25:39

    用try except,在except里写没有x3时的操作

    reply
    0
  • 三叔

    三叔2016-11-10 16:25:26

    get_json.has_key('x3')

    reply
    0
  • Cancelreply