Home > database >  Dumping to Json overwrites whats currently in Json
Dumping to Json overwrites whats currently in Json

Time:12-26

I want to create a json filled with channel and role ids for each guild the bots in for Twitch notifications later. The code just takes what the user wants the notif channel and streamer role to be and then dumps it in the json, and it works fine fore one server but when you try the command on a different server it just overwrites whats in the json.

Here is my code

async def TwitchSetup(ctx, RoleID = "", ChannelID = ""):
    guild = ctx.message.guild
    print(guild)
    data = {}
    data[guild.id] = []
    data[guild.id].append(ChannelID)
    data[guild.id].append(RoleID)
    with open("TwitchIds.json", "w") as file:
        json.dump(data, file, indent=4)

Im trying to get it so every time the command is run the json is updated so that the new server ids are added if the server doesn't already have a set of channel & role ids with a matching guild id.

Any help is much appreciated

CodePudding user response:

If you want to update existing JSON file, you will have to read it first and then modify it (if I am getting your question correctly):

import os

async def TwitchSetup(ctx, RoleID = "", ChannelID = ""):
    guild = ctx.message.guild
    jsonpath = "TwitchIds.json"
    data = {}
    if os.path.exists(jsonpath):
       with open(jsonpath, "r") as jf:
           data = json.loads(jf.read())
    
    if data.get(guild.id) and isinstance(data.get(guild.id), type([])):
        data[guild.id].append({"ChannelID": ChannelID, "RoleID": RoleID})
    else:
        data[guild.id] = [{"ChannelID": ChannelID, "RoleID": RoleID}]

    with open(jsonpath, "w") as file:
        json.dump(data, file, indent=4)

CodePudding user response:

Mode w clears the existing file before writing to it. You need mode a, which appends to end of the file. open() docs.

with open("TwitchIds.json", "a") as file:

CodePudding user response:

I recommend trying this for multiple servers.

import json

with open("TwitchIds.json") as dbF:
    db = json.load(dbF)
async def TwitchSetup(ctx, server = "", RoleID = "", ChannelID = ""):
    if server in data["servers"]:
        print(server)
        # remove data var, use db
        db["servers"][server] = {}
        db["servers"][server]["channelIds"].append(ChannelID)
        db["servers"][server]["roleIds"].append(RoleID)
        with open("TwitchIds.json", "w") as file:
            json.dump(db, file, indent=4)

And TwitchIds.json should be the following:

{
    "servers": {
        "myServerName": {
            "channelIds": [], "roleIds": []
        }
    }
}
  • Related