【发布时间】:2015-12-04 01:01:00
【问题描述】:
我有以下格式的 JSON:
{
"type":"MetaModel",
"attributes":[
{
"name":"Code",
"regexp":"^[A-Z]{3}$"
},
{
"name":"DefaultDescription",
},
]
}
attributes["regexp"] 是可选的。当我尝试访问像 attribute["regexp"] 这样的字段时,我收到的错误是
KeyError: 'regexp'
假设是,如果该字段不存在,那么它将被视为 NULL。
如何访问可选字段?
【问题讨论】:
-
attributes[0]["regexp"] -
您可以使用 attributes.get('regexp') 来完成。如果未找到密钥,则返回 None。