如何在python中验证key是否有值? 我有这个:
"version3.0" : {
"customizationInfo" : {
"surfaces" : [ {
"name" : "Custom Name",
"areas" : [ {
"customizationType" : "TextPrinting",
"colorName" : "black",
"fill" : "#000",
"fontFamily" : "Red",
"Dimensions" : {
"width" : 367,
"height" : 94
},
"Position" : {
"x" : 14,
"y" : 96
},
"name" : "Name Requested",
"label" : "Demo label",
"text" : "Need To Validate This"
} ]
}, {
"name" : "Gift Message Options",
"areas" : [ {
"customizationType" : "Options",
"name" : "Gift Message Options",
"label" : "Gift Message Options",
"optionValue" : ""
} ]
}, {
"name" : "Name of Gift Giver",
"areas" : [ {
"customizationType" : "TextPrinting",
"colorName" : "black",
"fill" : "#000",
"fontFamily" : "Green",
"Dimensions" : {
"width" : 380,
"height" : 151
},
"Position" : {
"x" : 12,
"y" : 158
},
"name" : "Name of Gift Giver",
"label" : "Name of Gift Giver",
"text" : ""
} ]
} ]
}
}
我在试着
custom_name = json_file['version3.0']['customizationInfo']['surfaces'][0]['areas'][0]['text']
如果此字段不是空的,则可以正常工作,如果不是空的。 我尝试了很多方法来验证,但是由于我对Python不太熟悉,所以无法进行正确的验证。 这不起作用:
if json_file['version3.0']['customizationInfo']['surfaces'][0]['areas'][0]['text']:
custom_name = json_file['version3.0']['customizationInfo']['surfaces'][0]['areas'][0]['text']
else:
custom_name = 'empty'
给出错误: KeyError('文本',))
Python。如何检查json中是否存在值?你知道吗
使用
.get('key', {})
并提供默认值。如果您希望得到一个列表,则输入一个默认值[]
,如果您希望得到一个dict,则输入一个默认值{}
。这可以确保您的代码永远不会中断。你知道吗这个问题也可以帮助你理解永远不要使用
dict[key]
而总是使用dict.get('key')
-Why dict.get(key) instead of dict[key]?试试这个
相关问题 更多 >
编程相关推荐