代码之家  ›  专栏  ›  技术社区  ›  schizophrenic

使用python修改JSON数据

  •  1
  • schizophrenic  · 技术社区  · 3 年前

    我正在用python编写一个discord bot,我有一个命令,可以抓取discord服务器上的每个用户,并将他们放在JSON文件中,我将其设置为JSON文件中已经存在一个人,然后它将他们第二次添加到他们的节中,但我在制作它时遇到了问题。这是我用来将所有内容放在JSON中的代码:

    import discord
    from discord import app_commands
    from discord.ext import commands
    import json
    from datetime import date
    
    @commands.command()
    async def forceScrape(ctx):
        schizo = 1133822869177126942 #my discord id
        debugchannel = bot.get_channel(1134732572816068628) #debug channel
        if ctx.message.author.id == schizo: #check if the user is me
            with open("users.json", "r") as f:
                users = json.load(f) #load json file
    
            for members in ctx.guild.members:
                currentDate = date.today() #getting current date
                usersid = members.id #getting every memebers' ids
                names = members.name #getting every members' name
                if str(usersid) in users:
                    users[usersid] = [{f"{users[str(usersid)]}\n" + f"{currentDate}":names}] #updating users[usersid] to add new datas
                    await debugchannel.send(f"ID: {usersid} NAME: {names} || was updated") #send a message in the debug channel
                else:
                    users[usersid] = [{f"{currentDate}":names}] #add new datas in users[usersid]
                    await debugchannel.send(f"ID: {usersid} NAME: {names} || was added") #send a message in debug channel
    
            with open("users.json", "w") as f:
                json.dump(users, f, indent=4) #put everything in users.json
    
            await debugchannel.send("Users have been scraped to users.json")
        else:
            await ctx.reply("You do not have permissions to execute that command")
    

    当它向已经存在的用户添加新数据时,它是这样的:

    {
        "1133822869177126942": [
            {
                "[{'2023-07-30': 'schizophrenic'}]\n2023-07-30": "schizophrenic"
            }
        ]
    }
    

    我试着让它看起来像这样:

    {
        "1133822869177126942": [
            {
                "2023-07-30": "schizophrenic"
            },
            {
                "2023-07-30": "schizophrenic"
            }
        ]
    }
    

    我寻找了多种方法来实现这一点,但找不到任何可行的方法,所以这是我的最后手段。

    我尽可能详细地介绍了代码,使您更容易理解。

    提前谢谢。

    1 回复  |  直到 3 年前
        1
  •  1
  •   mathbike    3 年前

    首先,你的字典是一个字符串,你不可能在字典里有双重含义,也不可能在这样的字典里有字典。

    这是你想要的吗?(不允许重复密钥)

    {
        "1133822869177126942": {
            "2023-07-30": "schizophrenic",
            "2023-07-31": "schizophrenic"
        }
    
    }
    

    还是要使用列表?(将允许重复)

    {
        "1133822869177126942": [
            {"2023-07-30": "schizophrenic"},
            {"2023-07-30": "schizophrenic"}
    
        ]
    }
    

    这是一个格式问题。弄清楚你的格式,然后根据格式构建你的代码。

    据我所见,我认为你应该使用一个列表,第二个选项。

    如果要使用嵌套词典,请将其正确格式化 https://www.w3schools.com/python/python_dictionaries_nested.asp