简体   繁体   English

蟒蛇。 如何检查json是否存在值?

[英]Python. How to check if values exists at json?

How to validate in python if key has value? 如果键有值,如何在python中验证? I have this: 我有这个:

"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" : ""
    } ]
  } ]
}

} }

I'm trying to get 我在努力

custom_name = json_file['version3.0']['customizationInfo']['surfaces'][0]['areas'][0]['text']

If this field is not empty it works fine, if empty is not. 如果该字段不为空,则工作正常,如果不为空,则工作正常。 I tried a lot of ways to validate, but as i'm not familiar with Python too close i can't make correct validation. 我尝试了多种验证方法,但是由于我对Python不太熟悉,因此无法进行正确的验证。 This doesn't works: 这不起作用:

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'

Gives error: KeyError('text',)) 给出错误:KeyError('text',))

Python. 蟒蛇。 How to check if values exists at json? 如何检查json是否存在值?

Try this 尝试这个

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'

Use .get('key', {}) and provide a default value. 使用.get('key', {})并提供默认值。 If you expect a list then put a default value of [] and if you expect a dict put a default value {} . 如果期望列表,则将默认值设置为[] ,如果期望字典将默认值设置为{} This ensures your code never breaks. 这样可以确保您的代码永不中断。

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', "")

This SO question will also help you understand to never use dict[key] and always use dict.get('key') - Why dict.get(key) instead of dict[key]? 这样的问题还将帮助您理解从不使用dict[key]并始终使用dict.get('key') - 为什么要用dict.get(key)而不是dict [key]?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM