json文件的保存,当遇到bytes格式无法序列化的问题解决方法

class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        try:
            if isinstance(obj, bytes):
                return str(obj, encoding='utf-8')
            return json.JSONEncoder.default(self, obj)
        except UnicodeDecodeError:
            pass
    

def save_file(data):
        with open('regedit.json', 'r', encoding='utf-8') as f:
            origin = json.load(f)
        origin.append(data)
        with open('regedit.json', 'w', encoding='utf-8') as f:
            json.dump(origin, f, cls=MyEncoder, ensure_ascii=False)

  

猜你喜欢

转载自www.cnblogs.com/caozhi00/p/10084271.html