How to write in json file in python?

Question:

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?

Asked By: Mohit Narwani

||

Answers:

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)
Answered By: CodeMonkey
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.