Home > Blockchain >  Having an issue parsing through this json in python
Having an issue parsing through this json in python

Time:03-25

I have created a var that is equal to t.json. The json dict is described below.

{
    "groups": {
        "customerduy": {
            "nonprod": {
                "name": "customerduynonprod",
                "id": "529646781943",
                "owner": "[email protected]",
                "manager_email": ""
            },
            "prod": {
                "name": "phishing_duyaccountprod",
                "id": "241683454720",
                "owner": "[email protected]",
                "manager_email": ""
            }
        },
        "customerduyprod": {
            "nonprod": {
                "name": "phishing_duyaccountnonprod",
                "id": "638968214142",
                "owner": "[email protected]",
                "manager_email": ""
            }
        },
        "ciasuppliergenius": {
            "prod": {
                "name": "ciasuppliergeniusprod",
                "id": "220753788760",
                "owner": "[email protected]",
                "manager_email": "[email protected]"
            }
        }
    }
}

my goal was to pars this json file and get value for "owner" and output it to a new var. example below:

t.json = group_map
group_id_aws = group(
            group.upper(), 
            "accounts", 
            template, 
            owner = group_map['groups']['prod'], 
            manager_description = "Groups for teams to access their product accounts.", 

the error I keep getting is: KeyError: 'prod'

CodePudding user response:

You get a key error since the key 'prod' is not in 'groups' What you have is

group_map['groups']['customerduy']['prod']
group_map['groups']['ciasuppliergenius']['prod']

So you will have to extract the 'prod' from each element.

CodePudding user response:

Owner occurs 4 times, so here is how to get all of them.


import json

# read the json
with open("C:\\test\\test.json") as f:
    data = json.load(f)

# get all 4 occurances
owner_1 = data['groups']['customerduy']['nonprod']['owner']
owner_2 = data['groups']['customerduy']['prod']['owner']
owner_3 = data['groups']['customerduyprod']['nonprod']['owner']
owner_4 = data['groups']['ciasuppliergenius']['prod']['owner']

# print results
print(owner_1)
print(owner_2)
print(owner_3)
print(owner_4)


the result:

[email protected]
[email protected]
[email protected]
[email protected]
  • Related