解析Json的可选字段

MSD*_*MSD -1 python regex json

我有以下格式的JSON:

{  
    "type":"MetaModel",
    "attributes":[  
        {  
            "name":"Code",
            "regexp":"^[A-Z]{3}$"
        },
        {
            "name":"DefaultDescription",
        },
   ]
}
Run Code Online (Sandbox Code Playgroud)

attributes["regexp"]是可选的.当我尝试访问该字段时attribute["regexp"],我收到错误

KeyError: 'regexp'
Run Code Online (Sandbox Code Playgroud)

假设是,如果该字段不存在则将其视为NULL.

如何访问可选字段?

Bur*_*lid 8

使用get,一种字典方法,None如果一个键不存在将返回:

foo = json.loads(the_json_string)
value = foo.get('regexp')
if value:
   # do something with the regular expression
Run Code Online (Sandbox Code Playgroud)

您也可以捕获异常:

value = None
try:
    value = foo['regexp']
except KeyError:
    # do something, as the value is missing
    pass
if value:
    # do something with the regular expression
Run Code Online (Sandbox Code Playgroud)