-2

How to validate in python if key has value? 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. 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',))

Python. How to check if values exists at json?

sbpython
  • 3
  • 1

2 Answers2

0

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'
Varun Mukundhan
  • 260
  • 2
  • 10
0

Use .get('key', {}) and provide a default value. 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]?

Subhrajyoti Das
  • 2,685
  • 3
  • 21
  • 36