Python-JSON文件操作简化的工具库,支持读取和修改

  • 这是一个关于python操控json的工具类
  • 可以利用get方法以路径的形式查看内容,输出的格式为列表或字典
  • change方法用于修改指定路径下的内容,支持修改内容为字典和列表的形式
  • 修改后使用save方法进行保存

以下是代码:

import json
import time
import random


class Error_message:
    def __init__(self):
        self.path_error = '路径错误!'


class MainException(Exception):
    pass


class Control_Json:
    def __init__(self):
        self.path = '/you/json/path'
        self.conf = open(self.path, 'r+')
        self.file = json.load(self.conf)

    def get(self, path):
        """
        输入路径获取路径下的内容
        """
        current_data = self.file
        for key in path.split('.'):
            # 如果 key 是数字,表示是列表的索引
            if key.isdigit():
                key = int(key)
                if isinstance(current_data, list) and key < len(current_data):
                    current_data = current_data[key]
                else:
                    return False
            elif key in current_data:
                current_data = current_data[key]
            else:
                return False
        return current_data

    def change(self, path, change_content):
        """
        修改指定路径下的内容,仅限于修改单个值
        """
        keys = path.split('.')
        current_data = self.file
        # 遍历路径,找到最终要修改的值所在的位置
        for key in keys[:-1]:
            if key.isdigit():
                key = int(key)
                if isinstance(current_data, list) and key < len(current_data):
                    current_data = current_data[key]
                else:
                    raise MainException(Error_message().path_error)
            elif key in current_data:
                current_data = current_data[key]
            else:
                raise MainException(Error_message().path_error)
        # 修改指定路径下的内容
        last_key = keys[-1]
        if last_key.isdigit():
            last_key = int(last_key)
            if isinstance(current_data, list) and last_key < len(current_data):
                current_data[last_key] = change_content
            else:
                raise MainException(Error_message().path_error)
        elif last_key in current_data:
            current_data[last_key] = change_content
        else:
            raise MainException(Error_message().path_error)

    def save(self):
        """
        保存修改后的 JSON 数据到文件
        """
        with open(self.path, 'w') as file:
            json.dump(self.file, file, indent=2)

posted @ 2023-11-28 17:37  liuada  阅读(91)  评论(0)    收藏  举报