如何在没有 [] 的情况下从 json 中获取 ID?

时间:2021-05-15 00:27:04

标签: json discord.py

有没有办法使用不同的东西来获取 json 文件中没有 [] 的 ID,而不需要删除或添加一些东西?我只知道“追加”和“删除”,而 readgetloadcheck 之类的东西不起作用。问号在那里我需要正确的词。如果我只输入 f'Name: <@{json_dict["blockedUser"]>',我只会得到 [] 中的 ID,<@> 就在那里。我很想看到一个解决方案。如果可能,我会显示 user.display_name 而不是 Name: 中的提及。感谢您的帮助!

    @commands.command(name='checkblock')  # checks if a user is on the list of blocked users
    async def checkblock(self, ctx):
        user = User
        with open('./bot_config/blocked_users.json', 'r') as json_file:
            json_dict = json.load(json_file)
        await ctx.send('Here are the blocked users:\n'
                       f'Name: <@{json_dict["blockedUser"]???(user.id)}>'
                       f'ID: {json_dict["blockedUser"].???(user.id)}')
        return

这是我的 .json 文件,里面有一个 ID。

{
    "blockedUser": [
        360881524410810380
    ]
}

1 个答案:

答案 0 :(得分:1)

json_dict["blockedUser"] 是一个列表,所以你可以遍历它的内容:

@commands.command(name='checkblock')  # checks if a user is on the list of blocked users
async def checkblock(self, ctx):
    with open('bot_config/blocked_users.json') as file:
        json_dict = json.load(file)

    template = 'Name: <@{}> (ID: {})'
    member_list = '\n'.join([template.format(id, id) for id in json_dict])
  
    await ctx.send(f'Here are the blocked users:\n{member_list}')

如果你想要成员的 display_name,你必须得到 discord.Member 对象,或者使用: