O'Reilly logo

Learn Python Programming by Fabrizio Romano

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required