我们都知道json.loads() 和 json.dumps() 分别用来将字符串装换成 json 和 将 json 转换成字符串,那读取 json 文件怎么 *** 作呢,下面我们来看一下:
结论使用 json.load 来读取 json 文件内容,json.dump()来格式化内容到json文件
读取 json 文件with open("test.json", "r") as json_file: json_dict = json.load(json_file) print(json_dict) print("type(json_dict) = >", type(json_dict)) print(json.dumps(json_dict, indent=4))输出结果:
[{'name': 'zhangsan', 'age': 23}, {'name': 'lisi', 'age': 24}] type(json_dict) = >写入 json 文件[ { "name": "zhangsan", "age": 23 }, { "name": "lisi", "age": 24 } ]
dict = [ { "name": "zhangsan", "age": 23 }, { "name": "lisi", "age": 24 } ] with open("test.json", "w") as json_file: json_dict = json.dump(dict, json_file)运行结果
test.json文件多了此次写入的内容
参考:python读写json文件
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)