Get item in dictionary inside list from JSON - Python

Viewed 126

I need to get the name information, inside the "object" list.

In this example I need this information (10.0.0.19)

"sourceNetworks":{
      "objects":[
         {
            "type":"Host",
            "overridable":false,
            "id":"005056BF-7C6E-0ed3-0000-012884911113",
            "name":"**10.0.0.19**"
         }
      ]
   }

I can get any information that is not in the "objects" lists with the command example_json[['metadata']['accessPolicy']['name']

and I get the "mb-test-01" information correctly from the json, but I don't know the syntax to get the items inside the "object" list.

to create this json I use in GET request this way

example_json = requests.get(f"https://{hostname}/api/fmc_config/v1/domain/{uuid}/policy/accesspolicies/{acp_id}/accessrules?expanded=true",headers=header_acp, verify=False).json()

follow the full json.

    {
       "metadata":{
          "ruleIndex":1,
          "section":"Mandatory",
          "category":"--Undefined--",
          "accessPolicy":{
             "type":"AccessPolicy",
             "name":"mb-test-01",
             "id":"005056BF-7C6E-0ed3-0000-012884914323"
          },
          "timestamp":1635219651530,
          "domain":{
             "name":"Global",
             "id":"e276abec-e0f2-11e3-8169-6d9ed49b625f",
             "type":"Domain"
          }
       },

   "links":{
      "self":"https://fmcrestapisandbox.cisco.com/api/fmc_config/v1/domain/e276abec-e0f2-11e3-8169-6d9ed49b625f/policy/accesspolicies/005056BF-7C6E-0ed3-0000-012884914323/accessrules/005056BF-7C6E-0ed3-0000-000268434442"
   },
   "enabled":true,
   "action":"ALLOW",
   "type":"AccessRule",
   "id":"005056BF-7C6E-0ed3-0000-000268434442",
   "sourceNetworks":{
      "objects":[
         {
            "type":"Host",
            "overridable":false,
            "id":"005056BF-7C6E-0ed3-0000-012884911113",
            "name":"10.0.0.19"
         }
      ]
   },
   "destinationNetworks":{
      "objects":[
         {
            "type":"Host",
            "overridable":false,
            "id":"005056BF-7C6E-0ed3-0000-012884911491",
            "name":"192.168.0.39"
         }
      ]
   },
   "logBegin":false,
   "logEnd":false,
   "variableSet":{
      "name":"Default-Set",
      "id":"76fa83ea-c972-11e2-8be8-8e45bb1343c0",
      "type":"VariableSet"
   },
   "logFiles":false,
   "enableSyslog":false,
   "vlanTags":{
      
   },
   "sendEventsToFMC":false,
   "name":"rule-1"
}
1 Answers

Presumably you want to retrieve all "name"s under "objects" keys so you could use a recursive function:

def get_name(d):
    for k,v in d.items():
        if k=='objects':
            for i in v:
                yield i.get('name')
        elif isinstance(v, dict):
            yield from get_name(v)

names = list(get_name(data))

Output:

['10.0.0.19', '192.168.0.39']
Related