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 Web Development with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.