Custom encoding/decoding with JSON

In the JSON world, we can consider terms like encoding/decoding as synonyms to serializing/deserializing. They basically all mean transforming to and back from JSON. In the following example, I'm going to show you how to encode complex numbers:

# json_examples/json_cplx.pyimport jsonclass ComplexEncoder(json.JSONEncoder):    def default(self, obj):        if isinstance(obj, complex):            return {                '_meta': '_complex',                'num': [obj.real, obj.imag],            }        return json.JSONEncoder.default(self, obj)data = {    'an_int': 42,    'a_float': 3.14159265,    'a_complex': 3 + 4j,}json_data = json.dumps(data, cls=ComplexEncoder)print(json_data)def object_hook(obj):    try:        if obj['_meta'] == '_complex':            return complex(*obj['num']) except (KeyError, ...

Get Learn Python Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.