我有以下格式的JSON:
{
"type":"MetaModel",
"attributes":[
{
"name":"Code",
"regexp":"^[A-Z]{3}$"
},
{
"name":"DefaultDescription",
},
]
}
attributes["regexp"]
是可选的。当我尝试访问attribute["regexp"]
这样的字段时,我收到错误
KeyError: 'regexp'
假设是,如果该字段不存在,那么它将被视为NULL。
如何访问可选字段?
答案 0 :(得分:7)
使用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
答案 1 :(得分:2)
您可以使用attributes[0]['regexp']
,因为regexp位于attribtues列表
答案 2 :(得分:0)
>>>data = {
"type":"MetaModel",
"attributes":[
{
"name":"Code",
"regexp":"^[A-Z]{3}$"
},
{
"name":"DefaultDescription",
},
]
}
>>>>c = data['attributes'][0].get('regexp')
>>>>print c # >>> '^[A-Z]{3}$'