refer:https://www.cnblogs.com/xiehong/p/9050301.html
pyton中与读写json文件相关的函数有四个:json.dumps(),json.loads(),json.dump(),json.load(),使用之前都需要导入json模块。我经常使用的方法是json.dumps()与json.loads()。
该函数将Python对象编码为JSON对象,可直接写入JSON文件中。
impotr json dic = {"xm":{"name":"xiaoming","age":20},"xh":{"name":"xiaohong","age":19}} # 字典转换为JSON,加上ensure_ascii=False可以识别中文,indent=4表示显示时间隔四个空格 print(json.dumps(dic,ensure_ascii=False,indent=4)) # 结果如下所示 { "xm": { "name": "xiaoming", "age": 20 }, "xh": { "name": "xiaohong", "age": 19 } } #若想写为json文件,则直接写入json.dumps()的结果即可 with open('./data.json','w',encoding='utf-8') as fw: fw.write(json.dumps(dic,ensure_ascii=False,indent=4))
使用json.loads()可以将json字符串变为python的对象。
import json # dic为写入文件中的json字符串对应的字典 dic = {"xm":{"name":"xiaoming","age":20},"xh":{"name":"xiaohong","age":19}} with open('./data.json','r',encoding='utf-8') as fr: jdic = json.loads(fr.read()) print(jdic) # 打印的结果与dic内容一致
json.dump()将对象编码成JSON字符串,并写入文件中,需要传入文件对象。
import json dic = {"xm":{"name":"xiaoming","age":20},"xh":{"name":"xiaohong","age":19}} with open('./data1.json','w',encoding='utf-8') as fw: json.dump(dic,fw,ensure_ascii=False,indent=4)
json.load()把JSON串变为Python的字典对象,需要传入文件对象。
import json with open('./data1.json','r',encoding='utf-8') as fr: print(json.load(fr))
a
--
123456789
更改id为3
--
test
更改id为2
--
commentor
伪造名称???
--
hhh
伪造名称???
--
yayay