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)