Home > Back-end >  How to get a nested response data from json python
How to get a nested response data from json python

Time:12-04

I call an API and this my JSON response:

{'data': [{
   'id': 'd-1225959', 
   'startTime': '2022-12-30T00:00:00.000Z', 
   'endTime': '2022-12-30T23:59:00.000Z', 
   'checkedInAt': None, 
   'checkedOutAt': None, 
   'status': 'PENDING', 

'space': {
   'id': 'd-4063963', 
   'name': '082', 
   'type': 'DESK', 
   'createdAt': '2021-07-06T11:48:57.000Z', 
   'updatedAt': '2021-07-06T11:48:57.000Z', 
   'isAvailable': False, 
   'assignedTo': None, 
   'locationId': '133778', 
   'floorId': '41681', 
   'floorName': 'Car Park', 
   'neighborhoodId': '92267', 
   'neighborhoodName': 'NEI1'}}

I'm struggling to get the 'space' 'id' and 'name' extracted out if I do a nested python loop like so it only returns the headers like 'id' and 'name' not the values held within.

for order in response['data']:
        print(order['id'])
        print(order['startTime'])
        print(order['endTime'])
        print(order['checkedInAt'])
        print(order['checkedOutAt'])
        print(order['status'])
        print(order['space'])
        for doc in response['space']:
            print(doc['id'], doc['name'])

Any help with this would be much appreciated!

CodePudding user response:

for doc in response['space']: will iterate over the keys in response['space'] dict, i.e. doc will be str.

You want to do doc = response['space'] instead and then print(doc['id']). or directly print(response['space']['id']).

Note, you may want to use dict.get() method to avoid KeyError.

# if response dict has no 'space' key, return empty dict.
# if no 'id' key - return None
space_id = response.get('space', {}).get('id') 
  • Related