0% found this document useful (0 votes)
30 views

Custom JSON Encoding

The document discusses custom JSON encodings and how to serialize objects to JSON. It covers using a custom callable with the JSONEncoder to serialize nested dictionaries and lists. It also discusses specifying a custom encoding function using the default argument of dump/dumps and implementing a single dispatch generic function.

Uploaded by

sandipmondal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Custom JSON Encoding

The document discusses custom JSON encodings and how to serialize objects to JSON. It covers using a custom callable with the JSONEncoder to serialize nested dictionaries and lists. It also discusses specifying a custom encoding function using the default argument of dump/dumps and implementing a single dispatch generic function.

Uploaded by

sandipmondal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

© 2019 MathByte Academy

Custom Encodings

As we saw in the previous video, any object can be serialized to JSON

cumbersome à remember to call the JSON serializer for every class

how do we do it for nested dictionaries and lists?

dump dumps

à can provide custom callable

à uses a default instance of JSONEncoder

à we can completely override JSONEncoder

© 2019 MathByte Academy


Specifying a Custom Encoding Function

One of the arguments of the dump / dumps function is default

à when provided, Python will call default if it encounters a type it cannot serialize
à argument must be a callable

à callable must have a single argument


à that argument will receive the object Python cannot serialize
à can include logic in our callable to differentiate between different types

à or we can use a single dispatch generic function


[ using the @singledispatch decorator from the functools module]

© 2019 MathByte Academy


Coding

© 2019 MathByte Academy

You might also like