首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用python列表创建动态JSON

使用python列表创建动态JSON
EN

Stack Overflow用户
提问于 2022-01-19 05:53:22
回答 1查看 60关注 0票数 -1

这是我在python文件中拥有的json结构。这里,stationList_of_state是一个python列表,它有大约5-10个值,这些值将根据代码动态变化。

代码语言:javascript
复制
        message = {
        "type": "template",
        "payload": {
            "template_type": "generic",
            "elements": 
            [
                {
                    "buttons": [
                            {
                                "title": stationList_of_state[1],
                                "payload": stationList_of_state[1],
                                "type": "postback"
                            }
                        ]
                    }
                ]
            }
        }

我尝试过这样的方法,它显示出错误:

代码语言:javascript
复制
        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"
                                }
                            ]
                        }
                    ]
                }
            }

有人能对我所做的提出另一种方法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-19 05:56:07

你就快到了

代码语言:javascript
复制
        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))
                ],
            },
        }

或者,简化for子句以省略不必要的i变量,

代码语言:javascript
复制
        message = {
            "type": "template",
            "payload": {
                "template_type": "generic",
                "elements": [
                    {
                        "buttons": [
                            {
                                "title": station,
                                "payload": station,
                                "type": "postback",
                            }
                        ]
                    }
                    for station in stationList_of_state
                ],
            },
        }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70765861

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档