# Python处理JSON文件的示例代码
import json
# 读取JSON文件
def read_json(file_path):
"""
读取JSON文件并返回解析后的Python对象。
参数:
file_path (str): JSON文件的路径
返回:
dict or list: 解析后的Python对象(通常是字典或列表)
"""
with open(file_path, 'r', encoding='utf-8') as file:
data = json.load(file)
return data
# 写入JSON文件
def write_json(file_path, data):
"""
将Python对象写入JSON文件。
参数:
file_path (str): 要写入的JSON文件路径
data (dict or list): 要写入的Python对象(通常是字典或列表)
"""
with open(file_path, 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=4)
# 示例用法
if __name__ == "__main__":
# 示例数据
example_data = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# 写入JSON文件
write_json('example.json', example_data)
# 读取JSON文件
loaded_data = read_json('example.json')
print(loaded_data)
json 模块来处理JSON数据。read_json 函数,接受文件路径作为参数,读取并解析JSON文件,返回Python对象(通常是字典或列表)。write_json 函数,接受文件路径和要写入的数据作为参数,将Python对象写入JSON文件。__main__ 中创建一个示例数据字典,调用 write_json 将其写入文件,再调用 read_json 读取并打印内容。这样可以方便地处理JSON文件的读写操作。
下一篇:python与人工智能
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站