Python: Edit JSON item from File

Viewed 48

I have the following code:

import json
with open("prefix.json", 'r+') as f:
    data = json.load(f)
def changeprefix(id, prefix):
    global data
    if not id in data:
        json.dump(data, open("prefix.json", "w"), indent = 4)
        data[id] = prefix
    else:
        // Code to edit existing item
changeprefix("6", "?")

It opens a file named prefix.json and I want to be able to edit an existing item, for example:

(Example.json)
{
    "item": "234"
}
 

How can I change item to something else in py, for example, to text here then save the file?

Thanks in Advance! (Also if you are going to dislike my question at least tell me what I can improve, I'm 13 and I have no idea what to do when people dislike my post without context)

1 Answers

All you have to do is assign to data["item"] and then write all of data into prefix.json!

data["item"] = "text here"
with open("prefix.json", "w") as f: # Makes sure to close the file
    json.dump(data, f, indent=4)
Related