目录
1. 从json文件读取数据
2. 将数据写入json文件
方法一:使用dump()函数
方法二:使用dumps()函数
完整代码
流程
json文件
Python 脚本
运行结果
控制台
base1.json
base2.json
使用load()函数获取json文件中的数据,并转换为Python的内置数据类型(列表或字典)。
下面自定义的函数read_json_file()实现了读取json文件数据的功能:
def read_json_file(url): """ Get the data for the json file. :param url: <str> json file path. :return: <dict/list> json file data. """ with open(url, "r") as json_file: data = json.load(json_file) json_file.close() return data
dump()函数可以将Python中的列表或字典写入到json文件中。可选参数indent指定缩进。
下面自定义的函数write_json_file_a()将数据写入到json文件中。
def write_json_file_a(data): """ Write Json file. :param data: <dict/list> data :return: <None> """ path = "base1.json" with open(path, "w") as json_file: json.dump(data, json_file, indent=6) json_file.close() print("Write %s success." % path) return
dumps()函数跟dump()函数的用法有所不同。dumps()先将Python列表或字典转换成特定的字符串格式,再借用open()和write()函数将转换后的数据写入到json文件中。可选参数indent指定缩进。
下面自定义的函数write_json_file_b()将数据写入到json文件中。
def write_json_file_b(data): path = "base2.json" data = json.dumps(data, indent=4) open(path, "w").write(data) print("Write %s success." % path) return
代码从base.json读取数据,再将读取后的数据分别写入base1.json文件(6缩进)和base2.json文件(4缩进)。
待读取的base.json如下所示:
[ { "name": "iphone X", "manufacturer": "Apple", "type": "mobile phone" }, { "name": "HuaweiCloud", "manufacturer": "Huawei", "type": "Virtual cloud technology" }, { "name": "Android", "manufacturer": "Google", "type": "mobile machines system" } ]
Python脚本在获取到json数据后打印在控制台上。然后分别使用两种写json文件的方式写入数据。
""" Note: Json actions demo. 1. Get Json data. 2. Write Json file. """ import json def read_json_file(url): """ Get the data for the json file. :param url: <str> json file path. :return: <dict/list> json file data. """ with open(url, "r") as json_file: data = json.load(json_file) json_file.close() return data def write_json_file_a(data): """ Write Json file. :param data: <dict/list> data :return: <None> """ path = "base1.json" with open(path, "w") as json_file: json.dump(data, json_file, indent=6) json_file.close() print("Write %s success." % path) return def write_json_file_b(data): path = "base2.json" data = json.dumps(data, indent=4) open(path, "w").write(data) print("Write %s success." % path) return if __name__ == "__main__": data = read_json_file("base.json") print("data: \n%s" % data) write_json_file_a(data) write_json_file_b(data)
base1文件中采用了6缩进写入。
[ { "name": "iphone X", "manufacturer": "Apple", "type": "mobile phone" }, { "name": "HuaweiCloud", "manufacturer": "Huawei", "type": "Virtual cloud technology" }, { "name": "Android", "manufacturer": "Google", "type": "mobile machines system" } ]
base2文件中采用了4缩进写入。
[ { "name": "iphone X", "manufacturer": "Apple", "type": "mobile phone" }, { "name": "HuaweiCloud", "manufacturer": "Huawei", "type": "Virtual cloud technology" }, { "name": "Android", "manufacturer": "Google", "type": "mobile machines system" } ]