[英]parsing the Json for the Optional fields
我有以下格式的 JSON:
{
"type":"MetaModel",
"attributes":[
{
"name":"Code",
"regexp":"^[A-Z]{3}$"
},
{
"name":"DefaultDescription",
},
]
}
attributes["regexp"]
是可選的。 當我嘗試訪問像attribute["regexp"]
這樣的字段時,我收到錯誤消息
KeyError: 'regexp'
假設是,如果該字段不存在,那么它將被視為 NULL。
如何訪問可選字段?
使用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 在屬性列表中
>>>data = {
"type":"MetaModel",
"attributes":[
{
"name":"Code",
"regexp":"^[A-Z]{3}$"
},
{
"name":"DefaultDescription",
},
]
}
>>>>c = data['attributes'][0].get('regexp')
>>>>print c # >>> '^[A-Z]{3}$'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.