0

I am storing the points of every user on a Discord server in a .json file. When a user deserves an extra point, the following code in run and their point increments in the .json file.

user_id = msg.author.id
user_name = msg.author.display_name
with open("firework_economy.json", 'r+') as f:
    data = json.load(f)
    if str(user_id) in data:
        print("Account already made")                       
        
        data[str(user_id)]["Fireworks"] += 1
        json.dump(data, f) 
    else:                              
        #data[str(user_id)] = {}
        data[str(user_id)]["Fireworks"] = 1
        json.dump(data, f)          
        await msg.channel.send(f"{msg.author.mention} earned 1 firework!")

I am expecting that the .json files changes from:

{
    "766571696491986965": {
        "Fireworks": 5}
}

to:

{
    "766571696491986965": {
        "Fireworks": 6}
}

But I am getting:

{
    "766571696491986965": {
        "Fireworks": 5}
}{"766571696491986965": {"Fireworks": 6}}
DRags
  • 64
  • 9
  • 2
    Maybe this can help you: https://stackoverflow.com/questions/13949637/how-to-update-json-file-with-python – NiiRexo Dec 29 '22 at 15:00
  • 1
    The above comment is indeed the correct solution to this. I'd just like to add that you should consider using an actual database instead of a JSON file. – stijndcl Dec 29 '22 at 15:00
  • Thankyou both. In terms of the database, would it take more storage/ram/cpu on a local server as the host for my discord bot's resources is quite limited. – DRags Dec 29 '22 at 15:14

1 Answers1

1

When you read fully the contents of a file, the file pointer gets to the end of the file. Hence when you are writing to it, you are writing at the end of the file.

Using f.seek(0, 0) before your json.dump(...) fixes your problem.

Martín Nieva
  • 476
  • 1
  • 5
  • 13