我有一个包含数据的json文件
{
"Theme": "dark_background"
}
我使用下面的代码来读取主题的值
import json
with open("setting.json", "r") as f:
stuff = json.load(f)
f.close()
style = stuff['Theme']
现在我想写/改变主题的值,怎么做呢?
我有一个包含数据的json文件
{
"Theme": "dark_background"
}
我使用下面的代码来读取主题的值
import json
with open("setting.json", "r") as f:
stuff = json.load(f)
f.close()
style = stuff['Theme']
现在我想写/改变主题的值,怎么做呢?
要以JSON格式序列化对象(列表、字典等),请使用json.dump()或json.dumps()函数.
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
要美化JSON输出,请使用indent参数.
with open("setting.json", "w") as fout:
json.dump(stuff, fout, indent=4)