Home > Back-end >  How to write in json file in python?
How to write in json file in python?

Time:12-13

I have a json file with data

{
  "Theme": "dark_background"
}

I am using below code to read the value of Theme

    import json
    with open("setting.json", "r") as f:
        stuff = json.load(f)
        f.close()
    style = stuff['Theme'] 

Now i want to write/change the value of Theme, How to do that?

CodePudding user response:

To serialize an object (list, dictionary, etc.) in JSON format use json.dump() or json.dumps() function.

import json
with open("setting.json", "r") as f:
    stuff = json.load(f)
style = stuff['Theme']
print("old:", style)

# set new value in dictionary
stuff["Theme"] = "light_background"
print("new:", stuff['Theme'])

# write JSON output to file
with open("setting.json", "w") as fout:
    json.dump(stuff, fout)

Output:

old: dark_background
new: light_background

To pretty-print the JSON output use the indent argument.

with open("setting.json", "w") as fout:
    json.dump(stuff, fout, indent=4)
  • Related