jsonUtil.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import json
  2. class JsonUtil:
  3. @staticmethod
  4. def read_json(file_path, encoding='utf-8'):
  5. """读取JSON文件"""
  6. try:
  7. with open(file_path, 'r', encoding=encoding) as f:
  8. return json.load(f)
  9. except FileNotFoundError:
  10. print("文件不存在")
  11. return None
  12. @staticmethod
  13. def write_json(data, file_path, encoding='utf-8'):
  14. """写入JSON到文件"""
  15. with open(file_path, 'w', encoding=encoding) as f:
  16. json.dump(data, f, ensure_ascii=False, indent=4)
  17. @staticmethod
  18. def update_json(file_path, updates, encoding='utf-8'):
  19. """更新JSON文件"""
  20. data = JsonUtil.read_json(file_path, encoding)
  21. if data is not None:
  22. data.update(updates)
  23. JsonUtil.write_json(data, file_path, encoding)
  24. @staticmethod
  25. def delete_key(file_path, key, encoding='utf-8'):
  26. """从JSON文件删除特定键"""
  27. data = JsonUtil.read_json(file_path, encoding)
  28. if data is not None:
  29. if key in data:
  30. del data[key]
  31. JsonUtil.write_json(data, file_path, encoding)
  32. else:
  33. print(f"键 '{key}' 不存在。")