0

I'm trying to access certain values from returned rest API output. I have converted to a dictionary and now I'm trying to access elements from the list, starting from "list": [

rest_response = {
                  "total": 2,
                  "offset": 0,
                  "limit": 25,
                  "list": [
                       {"id": 2233,
                        "url": "/v1/test/v2",
                        "enabled": true,
                        "info": {
                            "reason": "N/A",
                            "policy_name": "test",
                            "statuschk_tm": "2020-09-07 07:00:01",
                            "lock": "1",
                            "TYPE": "1"
                        }
                    ]
                 }

Previously I've been able to write a for loop a to search for values in the list, as below.

rest_response = rest_response['list']
for info in rest_response:
    id = info['id']
    print(id)

However, if I use a similar for loop to search for value that start after "info": { then I get a key error.

rest_response = rest_response['info']
for info in rest_response:
    name = info['policy_name']
    print(name)

I have viewed related posts but when I attempt to access I get "TypeError: list indices must be integers or slices, not str"

Python Accessing Nested JSON Data Having trouble with nested Python3 dictionary

Any ideas on what I can do to view values from "info": onwards?

Aaron
  • 65
  • 5

2 Answers2

0

Info is a dictionary in itself which contains policy-name which you cannot access directly. So you have to nest accordingly. This should work:

for x in rest_response:
    info = x['info']
    print(info['policy_name'])
Aairah
  • 18
  • 3
0

For accessing info dictionary you have to use the following code snippet -

rest_response['list'][0]['info']['policy_name']
David Buck
  • 3,752
  • 35
  • 31
  • 35