python - 将字典循环Python转换为Json

标签 python json loops dictionary telegram

我正在编写一个新的 Telegram Bot 。我创建了一个循环,将变量 i 插入到描述新按钮的字典 dic 中。但是当我在 Json 字典中转换 dic 时,它给了我这个问题。

import botogram
import json

bot = botogram.create("1210935912:AAG4X8vHlXLM3jQWnxFKDB2NsZ6pqTQM7lQ")
list = ["La","Alaska","New Delhi"]
bot.about = "Benvenuti"
@bot.command("start")
def start_command(chat, message):
    for i in list:
        dict = {
            'chat_id': chat.id,
            'text': 'Where are you?',
            'reply_markup': {
            'keyboard': [[
                {'text': i},
                {'text': 'Action B'},
            ],
            [
                {
                    'text': 'Use geolocation',
                    'request_location': True,
                },
            ],
        ],
        'resize_keyboard': True,
        'one_time_keyboard': True,
        'selective': True,
        }
    }
    bot.api.call('sendMessage', json.loads(dict))

if __name__ == "__main__":
     bot.run()

输出:

TypeError: the JSON object must be str, bytes or bytearray, not dict

最佳答案

json 是数据结构的文本表示。

json.loads 将 json 字符串转换为字典。由于您已经有一个字典,并且需要一个 json 字符串,因此您应该使用 json.dumps 方法。

关于python - 将字典循环Python转换为Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61229190/

相关文章:

javascript - 循环一个 JSON 脚本并在每个循环中应用到不同的 DIVS

python - 循环访问 DataFrame 中的行子集

python - 单击 python 时的 Tkinter 浮雕按钮

python - Tkinter OptionMenu 已禁用但可扩展

java - JSON - 如何对请求响应进行常见操作

javascript - For In循环,为什么无法通过obj.property访问属性值?

php - 如何生成优惠券代码,检查数据库是否唯一,如果不唯一则生成新的

python - 如何在 Pygame 中获取坐标/碰撞区域

python - 如何使用 Python 连接到本地 MQseries 队列?

php - 如何在 CakePHP Controller 中获取格式化的 JSON 输出