0

im trying to print a json in python

"rules":[
        {
            "table":"Forest",
            "format":"List",
            "header":{"en":"Forest","fr":"Forêt"},
            "fields":[
                {
                    "name":"Name",
                    "displayName":{"en":"Forest","fr":"Forêt"}
                },
                {
                    "name":"ForestMode",
                    "displayName":{"en":"Forest Mode","fr":"Mode forêt"},
                    "ok":"re.search('Windows(2019|2016)Forest',x) != None",
                    "warn":"re.search('Windows(2012R2|2012)Forest',x) != None",
                    "nok":"re.search('Windows(2008R2|2008|2003|2003Interim|2000)Forest',x) != None",
                    "comment":{"en":"Increase the functional level of the forest","fr":"Augmenter le niveau fonctionnel de la forêt"}
                },
                {
                    "name":"RootDomain",
                    "displayName":{"en":"Root Domain","fr":"Domaine racine"}
                },
                {
                    "name":"Domains",
                    "displayName":{"en":"Domains","fr":"Domaines"}
                },
                {
                    "name":"Sites",
                    "displayName":{"en":"Sites","fr":"Sites"}
                },
                {

but i've run into an issue some of the json data doent have the key while some do i have written this thus far

with open('./rules-adds.json', 'r') as ad_file:
    ad_data = json.load(ad_file)
    #    print(ad_data)
    data = ad_data["rules"]
#    print(data)
#    print(json.dumps(ad_data, indent=4))
for x in data:
    print(x['table'], x['fields'])
    for y in x['fields']:
        print(y['name'])

But i get an error since the first element of the json file doesn't have the "ok" key

    print(y['ok'])
KeyError: 'ok'
ruleboy21
  • 5,510
  • 4
  • 17
  • 34
  • 2
    Does this answer your question? [Check if a given key already exists in a dictionary](https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary) – gre_gor Jun 03 '22 at 11:30
  • 1
    When you don't know about the keys that are present in the json, the easiest approach is to use recursion. – Huzaifa Qamer Jun 03 '22 at 11:31

1 Answers1

2

Answer:

You can use the get function of a dictionary:

my_value = my_dict.get('some_key_name', 'in_case_not_found')

So my_value will contain the existing value, or a default value you define in case there key doesn't exist in the dictionary

You can also check if a key exists with an if:

if 'some_key_name' in my_dict:
    print(my_dict['some_key_name'])
else:
    print('Well, key is not there')

Extra tip:

  • Make sure you anem your variables as descriptible as possible. So for field in fields ..., for attribute in my_dictionary ...