Python。如何检查json中是否存在值?

2024-09-29 23:25:28 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在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中是否存在值?你知道吗


Tags: oftextnamejsonmessagecustomlabeloptions
2条回答

使用.get('key', {})并提供默认值。如果您希望得到一个列表,则输入一个默认值[],如果您希望得到一个dict,则输入一个默认值{}。这可以确保您的代码永远不会中断。你知道吗

a = {'a': 1, 'b': 2}
print(a.get('c', {}).get('next_key', "NA"))
#NA

#For your code you can use
custom_name = json_file.get('version3.0', {}).get('customizationInfo', {}).get('surfaces', [])[0].get('areas', [])[0].get('text', "")

这个问题也可以帮助你理解永远不要使用dict[key]而总是使用dict.get('key')-Why dict.get(key) instead of dict[key]?

试试这个

if 'text' in json_file['version3.0']['customizationInfo']['surfaces'][0]['areas'][0]:               
    custom_name = json_file['version3.0']['customizationInfo']['surfaces'][0]['areas'][0]['text']
else:
    custom_name = 'empty'

相关问题 更多 >

    热门问题