Home > Software engineering >  How do I assign a value to a JSON key using a variable in Python?
How do I assign a value to a JSON key using a variable in Python?

Time:05-30

I'm trying to make a feature with a Discord bot where it counts how many commands have been run and it stores it on a JSON file named data.json. Here is the code:

import json

# Read 'data.json'
with open("data.json", "r") as d:
    datar = json.load(d)
com = datar.get("commands-run")

# Functions
def command_increase():
    commands_run = com   1
    dataw = open("data.json", "w")
    dataw["commands-run"] = commands_run

And here is the JSON file:

{
    "commands-run": 0
}

And this is the error I get when I run a command and it tries to increase the value in the JSON file:

TypeError: '_io.TextIOWrapper' object does not support item assignment

On top of that, it also completely wipes the JSON file. By that, I mean that it just clears everything. Even the brackets.

CodePudding user response:

When you do a json.load, it loads your json data into a dict. You can increase your command counter in this dict and re-write the dict back into your json file at the end of it.

import json

# Read 'data.json'
with open("data.json", "r") as d:
    datar = json.load(d)
com = datar.get("commands-run")

# Functions
def command_increase():
    commands_run = com   1
    datar["commands-run"] = commands_run
    with open("data.json", "w") as dataw:
        dataw.write(json.dumps(datar, indent=4))

command_increase()
  • Related