Python 解析可选字段的Json

Python 解析可选字段的Json,python,json,regex,Python,Json,Regex,我有以下格式的JSON: { "type":"MetaModel", "attributes":[ { "name":"Code", "regexp":"^[A-Z]{3}$" }, { "name":"DefaultDescription", }, ] } 属性[“regexp”]是可选的。当我试图访问像属性[“regexp

我有以下格式的JSON:

{  
    "type":"MetaModel",
    "attributes":[  
        {  
            "name":"Code",
            "regexp":"^[A-Z]{3}$"
        },
        {
            "name":"DefaultDescription",
        },
   ]
}
属性[“regexp”]
是可选的。当我试图访问像
属性[“regexp”]
这样的字段时,我得到的错误是

KeyError: 'regexp'
假设是,如果该字段不存在,则该字段将被视为空


如何访问可选字段?

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

foo = json.loads(the_json_string)
value = foo.get('regexp')
if value:
   # do something with the regular expression
您还可以捕获异常:

value = None
try:
    value = foo['regexp']
except KeyError:
    # do something, as the value is missing
    pass
if value:
    # do something with the regular expression

您可以使用
attributes[0]['regexp']
,因为regexp在attribtues列表中

attributes[0][“regexp”]
您可以使用attributes.get('regexp')。如果找不到密钥,则返回None。
    >>>data = {  
"type":"MetaModel",
"attributes":[  
    {  
        "name":"Code",
        "regexp":"^[A-Z]{3}$"
    },
    {
        "name":"DefaultDescription",
    },
]
}
    >>>>c = data['attributes'][0].get('regexp')
    >>>>print c # >>> '^[A-Z]{3}$'