# jsonHelper/jsonHelper.pyimport jsonimport osclass JsonHelper:@staticmethoddef encode(data, indent=2, ensure_ascii=False):"""将 Python 对象编码为 JSON 字符串:param data: dict/list 等对象:param indent: 缩进格式:param ensure_ascii: False 可输出中文:return: str"""try:return json.dumps(data, indent=indent, ensure_ascii=ensure_ascii)except (TypeError, OverflowError) as e:print(f"[JsonHelper.encode] JSON 编码失败: {e}")return ""@staticmethoddef decode(json_string):"""将 JSON 字符串解析为 Python 对象:param json_string: str:return: dict/list"""try:return json.loads(json_string)except json.JSONDecodeError as e:print(f"[JsonHelper.decode] JSON 解码失败: {e}")return None@staticmethoddef read_file(file_path):"""从文件读取 JSON 并解析为对象"""if not os.path.isfile(file_path):print(f"[JsonHelper.read_file] 文件不存在: {file_path}")return Nonetry:with open(file_path, "r", encoding="utf-8") as f:return json.load(f)except Exception as e:print(f"[JsonHelper.read_file] 读取失败: {e}")return None@staticmethoddef write_file(data, file_path, indent=2):"""将对象写入 JSON 文件"""try:with open(file_path, "w", encoding="utf-8") as f:json.dump(data, f, indent=indent, ensure_ascii=False)return Trueexcept Exception as e:print(f"[JsonHelper.write_file] 写入失败: {e}")return False
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。