在Json中转换dctionary循环python

2024-06-14 23:16:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个新的电报机器人编程。我创建了一个循环,在描述新按钮的dictionaridic中插入变量i。但是当我在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

Tags: textimportidjsontruebotchat机器人
2条回答

json是数据结构的文本表示

json.loads将json字符串转换为字典。因为您已经有了一个字典,并且想要一个json字符串,所以应该改用json.dumps方法

您需要使用json.dumps将对象转换为json

bot.api.call('sendMessage', json.dumps(dict))

相关问题 更多 >