PhunderDev
PhunderDev

Reputation: 1

Json overwriting previous line

I have a huge problem with my code and I wasn't able to find anything on the internet for the past 3 hours so I'm asking here. I'm trying to add the ctx.guild.id as a new variable to my json "queue.json" file but apparently every time I run this code, instead of adding a new variable in the new line it overwrites the previously added variable. Here's my code:

with open("queue.json", "r") as f:
    Queue = json.load(f)
    if not ctx.guild.id in Queue:
        with open("queue.json", "w") as QueueAddFile:
            NewQueueID = {ctx.guild.id : []}
            json.dump(NewQueueID, QueueAddFile, separators=(',', ':'))

Upvotes: 0

Views: 227

Answers (1)

Barmar
Barmar

Reputation: 781058

You're not adding the key to the Queue dictionary, you're creating a new dictionary that just has the one new ID in it. So when you rewrite the file, you're discarding all the other keys.

with open("queue.json", "r") as f:
    Queue = json.load(f)
if ctx.guild.id not in Queue:
    Queue[ctx.guild.id] = []
    with open("queue.json", "w") as QueueAddFile:
        json.dump(Queue, QueueAddFile, separators=(',', ':'))

Upvotes: 1

Related Questions