12345678910111213141516171819202122232425262728293031323334353637 |
- import json
- class JsonUtil:
- @staticmethod
- def read_json(file_path, encoding='utf-8'):
- """读取JSON文件"""
- try:
- with open(file_path, 'r', encoding=encoding) as f:
- return json.load(f)
- except FileNotFoundError:
- print("文件不存在")
- return None
- @staticmethod
- def write_json(data, file_path, encoding='utf-8'):
- """写入JSON到文件"""
- with open(file_path, 'w', encoding=encoding) as f:
- json.dump(data, f, ensure_ascii=False, indent=4)
- @staticmethod
- def update_json(file_path, updates, encoding='utf-8'):
- """更新JSON文件"""
- data = JsonUtil.read_json(file_path, encoding)
- if data is not None:
- data.update(updates)
- JsonUtil.write_json(data, file_path, encoding)
- @staticmethod
- def delete_key(file_path, key, encoding='utf-8'):
- """从JSON文件删除特定键"""
- data = JsonUtil.read_json(file_path, encoding)
- if data is not None:
- if key in data:
- del data[key]
- JsonUtil.write_json(data, file_path, encoding)
- else:
- print(f"键 '{key}' 不存在。")
|