Supporting JSON in our classes

In order to properly support creating strings in JSON notation, we need encoders and decoders for classes outside the types that can be converted automatically. To encode our unique objects into JSON, we need to provide a function that will reduce our objects to Python primitive types. The json module calls this a default function; it provides a default encoding for an object of an unknown class.

To decode strings in JSON notation and create Python objects of an application class, a class outside the baseline types supported by JSON, we need to provide an extra function. This extra function will transform a dictionary of Python primitive values into an instance of the one of our application classes. This is called the object hook function; it's used to transform dict into an object of a customized class.

The json module documentation suggests that we might want to make use of class hinting. The Python documentation includes a reference to the JSON-RPC version 1 specification (see http://json-rpc.org/wiki/specification). Their suggestion is to encode an instance of a customized class as a dictionary, like the following:

{"__jsonclass__": ["ClassName", [param1,...]]} 

The suggested value associated with the "__jsonclass__" key is a list of two items: the class name, and a list of arguments required to create an instance of that class. The specification allows for more features, but they're not relevant to Python.

To decode an object from a JSON dictionary, an object hook function can look for the "__jsonclass__" key as a hint that one of our classes needs to be built, not a built-in Python object. The class name can be mapped to a class object and the argument sequence can be used to build the instance.

When we look at other sophisticated JSON encoders (such as the one that comes with the Django Web framework), we can see that they provide a bit more complex an encoding of a custom class. They include the class, a database primary key, and the attribute values. We'll look at how to implement customized encoding and decoding. The rules are represented as simple functions that are plugged into the JSON encoding and decoding functions.

Let's see how to customize JSON encoding.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset