1. 程式人生 > >json檔案的儲存,當遇到bytes格式無法序列化的問題解決方法

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)