Defining a class of instance variable from commonly used fields in API response by looping through each JSON record
self.id=response['identifier'] -->output: 1234
self.name=response['FirstName'] -->output: ABCD
self.country_name=response['Country'] -->output: US
self.route_type=[j.get('route_type') or None for j in response['route_details']] -->output: ['Primary','Secondary']
self.route=[j.get('route_code') or None for j in response['route_details']] -->output: ['AX1','Ax2']
self.pin=[j.get('pin_code') or None for j in response['route_details']] -->output: ['4456','7654']
I am trying to create a nested response in below lines
Details: {
id: "1234",
name: "ABCD"
},
Country:{
country_name:"US"
}
Route_details: [
{route_type: "Primary", route: "AX1",pin: "4456"},
{route_type: "Secondary", route: "Ax2",pin: "7654"}
]
How to obtain the above response which is passed to downstream API as per its expected payload.
To make that output you only need to add a function to your class and build a big string with all of that data in it and return it. I have replicated your structure in this example code, and after adding this function to your class definition, which you didn't provide the name of so I guessed it could be
APIResponse, you can use it by just calling to get that output format you describe.Here is the code:
And this is what I get when I run that which looks just like your example: