0

Given my sample array:

  json_data = data: [
   {
     'item_name' : "bag",
    'item_price' : 12.99,
    'item_stock' : 55
    },
    {
     'item_name' : "jacket",
    'item_price' : 8.99,
    'item_stock' : 42
    },
    {
     'security_check' : "maximum",
     'item_name' : "jewelry",
     'item_stock' : 10
    },
    {
     'security_check' : "minimum",
     'item_name' : "leather",
     'item_stock' : 5
    }
    ]

i want to find elements with the "security_check" element. some elements do not have that and im trying to get the item_name of elements with security_check

This is the function im currently calling:

def array_parse_for_item_name(json_data, name):
    for entry in json_object:
        if entry["security_check"] in json_object:
          print(str(entry["item_name"]))
          print(str(entry["item_stock"]))

but right now all im getting is: KeyError: 'security_check' and i assume it's because some elements do not have that key

Any help would be much appreciated. Thanks in advance.

zoenightshade
  • 159
  • 2
  • 12
  • in your code `json_object` isn't defined at all, but it is used. Please post a [mcve]. Perhaps that is just a typo for `json_data` (or vice versa) but such typos don't belong in questions unless they are part of your actual code. – John Coleman Sep 29 '21 at 09:56

1 Answers1

0

Check if it is one of keys rather than try retrieve its' value, i.e. replace

if entry["security_check"] in json_object

using

if "security_check" in entry.keys()
Daweo
  • 31,313
  • 3
  • 12
  • 25