Creating a dynamic JSON using a python list

This is the json structure that I am having inside of a python file. Here the stationList_of_state is a python list which has some 5-10 values which will change dynamically based on the code.

        message = {
        "type": "template",
        "payload": {
            "template_type": "generic",
            "elements": 
            [
                {
                    "buttons": [
                            {
                                "title": stationList_of_state[1],
                                "payload": stationList_of_state[1],
                                "type": "postback"
                            }
                        ]
                    }
                ]
            }
        }

I have tried something like this which showed errors:

        message = {
            "type": "template",
            "payload": {
                "template_type": "generic",
                "elements": 
                [
                for i in range(len(stationList_of_state)):
                    {
                        "buttons": [
                                {
                                    "title": stationList_of_state[i],
                                    "payload": stationList_of_state[i],
                                    "type": "postback"
                                }
                            ]
                        }
                    ]
                }
            }

Can someone suggest an alternate approach to what I have did?


Solution 1:

You're almost there:

        message = {
            "type": "template",
            "payload": {
                "template_type": "generic",
                "elements": [
                    {
                        "buttons": [
                            {
                                "title": stationList_of_state[i],
                                "payload": stationList_of_state[i],
                                "type": "postback",
                            }
                        ]
                    }
                    for i in range(len(stationList_of_state))
                ],
            },
        }

or, simplifying the for clause to omit the unnecessary i variable,


        message = {
            "type": "template",
            "payload": {
                "template_type": "generic",
                "elements": [
                    {
                        "buttons": [
                            {
                                "title": station,
                                "payload": station,
                                "type": "postback",
                            }
                        ]
                    }
                    for station in stationList_of_state
                ],
            },
        }