【问题标题】:Converting dctionary loop python in Json在Json中转换字典循环python
【发布时间】:2020-07-28 10:47:57
【问题描述】:

我正在编写一个新的电报机器人。我创建了一个循环,将变量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.dumps(dict)

标签: python json loops dictionary telegram


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 它不起作用:请求失败,代码为 400。来自电报的响应:“错误请求:消息文本为空”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 2011-07-06
    • 2018-02-22
    • 1970-01-01
    • 2019-03-28
    • 2019-04-19
    相关资源
    最近更新 更多