Python convert class instance variable to nested structure

36 views Asked by At

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.

1

There are 1 answers

0
BitsAreNumbersToo On BEST ANSWER

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:

class APIResponse:
    def make_nested_response(self) -> str:
        out_format = ''
        out_format += ' ' * 4 + 'Details: {\n'
        out_format += ' ' * 4 + f'id: "{self.id}",\n'
        out_format += ' ' * 4 + f'name: "{self.name}"\n'
        out_format += ' ' * 4 + '},\n'
        out_format += ' ' * 4 + 'Country:{\n'
        out_format += ' ' * 4 + f'country_name:"{self.country_name}"\n'
        out_format += ' ' * 4 + '}\n'
        out_format += ' ' * 4 + 'Route_details: [\n'
        for route_type, route, pin in zip(self.route_type, self.route, self.pin):
            out_format += ' ' * 4 + f'{{route_type: "{route_type}", route: "{route}",pin: "{pin}"}},\n'
        out_format = out_format[:-2] + '\n'  # to cut off last comma
        out_format += ' ' * 4 + ']\n'
        return out_format


if __name__ == '__main__':
    apir = APIResponse()
    apir.id = 1234
    apir.name = 'ABCD'
    apir.country_name = 'US'
    apir.route_type = ['Primary', 'Secondary']
    apir.route = ['AX1', 'Ax2']
    apir.pin = ['4456', '7654']

    output = apir.make_nested_response()
    print(output)

And this is what I get when I run that which looks just like your example:

    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"}
    ]