Remi_Zacharias
Remi_Zacharias

Reputation: 328

How to add values to a key in python using a .json file

I am using .JSON files and the JSON Library to store information when it is passed in through discord. I'm storing the values like this:

{
    "key": {
        "value1": "value2"
    }
}

Whenever I pass in some new values in the same key, instead of adding the values below or above the current values, the values just change to the newest value.

What I want to have happen:

{
    "key": {
        "value1": "value2"
        "value3": "value4"
    }
}

What actually happens:

{
    "key": {
        "value3": "value4"
    }
}

Here is my code:

@commands.command()
    async def add_reaction_role(self, ctx, message_id, reaction, role):
        with open("data.json") as f:
            data = json.load(f)

        data[message_id] = {}
        # add keys to message_id like this
        data[message_id] = {reaction: role}
        # it will be like {"message_id": {"key1": {"another_key": "something"}}}

        with open('data.json', 'w') as f:
            json.dump(data, f, indent=4)  # indent for nice visualization

Anything would be helpfull, ask me if you need clarification on anything. Thanks!

Upvotes: 0

Views: 136

Answers (2)

GalaBoo
GalaBoo

Reputation: 9

comments are correct. just like to elaborate so you understand the issue here -

looks like what you want is:

{
    "key": {                 // message_id
        "value1": "value2"   // recation: role
        "value3": "value4"   // reaction: role
    }
}

but what you do is replacing all of the inner dict, instead of adding values.

{
    "key": **{
        "value1": "value2"   
        "value3": "value4"   
    }**
}

(when you do this: data[message_id] = {})

Upvotes: 1

deadshot
deadshot

Reputation: 9061

Problem is each time you are assigning a new dict so it will replaces the old value with current value and don't do this data[message_id] = {} instead use dict.setdefault()

with open("data.json") as f:
    data = json.load(f)

data.setdefault(message_id, {})
data[message_id][reaction] = role

Upvotes: 0

Related Questions