這是我在 python 檔案中的 json 結構。這里的 stationList_of_state 是一個 python 串列,它有 5-10 個值,這些值會根據代碼動態變化。
message = {
"type": "template",
"payload": {
"template_type": "generic",
"elements":
[
{
"buttons": [
{
"title": stationList_of_state[1],
"payload": stationList_of_state[1],
"type": "postback"
}
]
}
]
}
}
我嘗試過類似這樣的方法,但顯示錯誤:
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"
}
]
}
]
}
}
所有這些都存在于 python 檔案中。我希望實作的是創建一個 json 結構,它動態地從 python 串列中獲取值。
uj5u.com熱心網友回復:
你快到了:
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變數,
message = {
"type": "template",
"payload": {
"template_type": "generic",
"elements": [
{
"buttons": [
{
"title": station,
"payload": station,
"type": "postback",
}
]
}
for station in stationList_of_state
],
},
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/415093.html
標籤:
上一篇:為什么這似乎回傳一個陣列?
