ijl / orjson

Fast, correct Python JSON library supporting dataclasses, datetimes, and numpy
Apache License 2.0
6.29k stars 215 forks source link

Support default deserialization methods #490

Closed AharonSambol closed 5 months ago

AharonSambol commented 5 months ago

I added a default option for deserialization so that you can serialize and deserialize any type of object. I used const generics as to not loose any performance when not using this feature :)

e.g.

import orjson 
import decimal 

DECIMAL_TAG = "__DECIMAL__"
BYTEARRAY_TAG = "__BYTEARRAY__"

def default(obj):
    if isinstance(obj, decimal.Decimal):
        return {DECIMAL_TAG: str(obj)}
    if isinstance(obj, bytearray):
        return {BYTEARRAY_TAG: obj.hex()}
    raise TypeError()

serialized_json = orjson.dumps(
    {'pi': decimal.Decimal('3.14159'), 'data': bytearray(b'\x124\xab\xcd')}, 
    default=default
)

def deserialize_decimal(serialized_decimal: str) -> decimal.Decimal:
   return decimal.Decimal(serialized_decimal)

def deserialize_bytearray(serialized_bytearray: str) -> bytearray:
   return bytearray.fromhex(serialized_bytearray)

orjson.loads(
    serialized_json, 
    default={DECIMAL_TAG: deserialize_decimal, BYTEARRAY_TAG: deserialize_bytearray}
)