-1

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?

Mohit Narwani
  • 169
  • 2
  • 11

1 Answers1

0

To serialize an object (list, dictionary, etc.) in Python to the JSON format use the json library with either the json.dump() or json.dumps() function. The function json.dump() formats to a stream and json.dumps() returns a formatted JSON string.

import json

with open("setting.json", "r") as f:
    stuff = json.load(f)
style = stuff.get("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)
CodeMonkey
  • 22,825
  • 4
  • 35
  • 75