一、概述
在json的读写中主要涉及两种数据类型,字符串和json文件,读取后的数据主要用于传参,由于json文件读取到的数据无法进行直接传参,参数化的数据格式一般为元组格式,所以文件类型的格式读取后还要再做数据类型转换。
二、代码封装详解
下面先创建一个json_tool.py文件:
import json
import os
class JsonTool:
def __init__(self, file_path=None):
self.file_path = file_path
def read_from_file(self, file_path=None):
"""
从指定文件读取 JSON 数据。
如果未指定文件路径,则使用初始化时提供的路径。
"""
path = file_path or self.file_path
if not path:
raise ValueError("File path must be provided")
try:
with open(path, 'r', encoding='utf-8') as file:
json_data = json.load(file)
# json数据格式转化为列表
list_data = []
for item in json_data:
tmp = tuple(item.values())
list_data.append(tmp)
return list_data
except Exception as e:
raise RuntimeError(f"Failed to read JSON from file: {e}")
def read_from_string(self, json_string):
"""
从字符串读取 JSON 数据。
"""
try:
data = json.loads(json_string)
return data
except Exception as e:
raise RuntimeError(f"Failed to read JSON from string: {e}")
def write_to_file(self, data, file_path=None):
"""
将 JSON 数据写入指定文件。
如果未指定文件路径,则使用初始化时提供的路径。
"""
path = file_path or self.file_path
if not path:
raise ValueError("File path must be provided")
try:
with open(path, 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=4)
except Exception as e:
raise RuntimeError(f"Failed to write JSON to file: {e}")
def delete_file(self, file_path=None):
"""
删除指定的 JSON 文件。
如果未指定文件路径,则使用初始化时提供的路径。
"""
path = file_path or self.file_path
if not path:
raise ValueError("File path must be provided")
try:
os.remove(path)
except Exception as e:
raise RuntimeError(f"Failed to delete file: {e}")
# Example usage:
if __name__ == "__main__":
tool = JsonTool("example.json")
# Writing data to file
data = {"name": "John", "age": 30}
tool.write_to_file(data)
print("Data written to file")
# Reading data from file
data_from_file = tool.read_from_file()
print("Data from file:", data_from_file)
# Reading data from string
json_string = '{"name": "Jane", "age": 25}'
data_from_string = tool.read_from_string(json_string)
print("Data from string:", data_from_string)
# Deleting the file
tool.delete_file()
print("File deleted")
文件基础路径可以在项目根目录下创建配置文件config.py 全局变量一般使用大写
import os
BASE_DIR = os.path.dirname(__file__)
# print("__file__:", __file__)
print("BASE_DIR:", BASE_DIR)
三、使用举例:
1.写入 JSON 数据到文件
tool = JsonTool("example.json")
data = {"name": "John", "age": 30}
tool.write_to_file(data)
print("Data written to file")
2. 从文件读取 JSON 数据
data_from_file = tool.read_from_file()
print("Data from file:", data_from_file)
3. 从字符串读取 JSON 数据
json_string = '{"name": "Jane", "age": 25}'
data_from_string = tool.read_from_string(json_string)
print("Data from string:", data_from_string)
4. 删除 JSON 文件
tool.delete_file()
print("File deleted")