0

So I'm making a Discord bot and I need to edit some data in my .json file

Here's the json file:

enter image description here

"name"'s variable is player

I want to edit the balance, there's gonna be a command to add and subtract, so how do I do that?

I tried writing and deleting it, but either I did it wrong or it doesn't work

2
  • 4
    Show us how you did it. All you need to do is json.loads to convert this to a Python structure, then use regular Python code to make your change, then json.dumps to write it back out. Commented Mar 27, 2022 at 18:12
  • I suppose in this case json.dump and json.load are better choiches, since there is JSON as a file instead of as a string. But yes, the OP just has to read the documentation. Commented Mar 27, 2022 at 18:24

1 Answer 1

1

Python as a built-in module called json, that provides a json.JSONDecoder and a json.JSONEncoder class, a JSON (JavaScript Object Notation) parser (json.loads) and few other functions.


If you have your data.json file, you can convert it to Python...

import json
with open("data.json", 'r+') as file:
    my_data = json.load(file)

...edit it...

my_data["Key"] = "New Value"

...and encode it back

json.dump(my_data, file)
Sign up to request clarification or add additional context in comments.

6 Comments

I added this, and now what it does is add a fully new one: [ { "name": "name" "balance": 0.0 } ][{"name": "name", "balance": 10}] Is there a way to delete the old one and add the new one to the same set, or just update the new one?
I've been working for years with python's json module and it has never given me problems... can you edit your answer with the results you got?
imgur.com/a/bJG7RZj A link to an image of everything
Maybe because you appended (I mean APPENDED and not overwrited) a dictionary to data?
So how would I overwrite it?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.