Customizing JSON decoding

In order to decode objects from a string in JSON notation, we need to work within the structure of a JSON parsing. Objects of our customized class definitions were encoded as simple dicts. This means that each dict decoded by the JSON decoder could be one of our customized classes. Or, what is serialized as a dict should be left as a dict.

The JSON decoder object hook is a function that's invoked for each dict to see whether it represents a customized object. If dict isn't recognized by the hook function, it's an ordinary dictionary and should be returned without modification. Here's our object hook function:

def blog_decode(some_dict: Dict[str, Any]) -> Dict[str, Any]:
if set(some_dict.keys()) == {"__class__", "__args__", "__kw__"}:
class_ = eval(some_dict["__class__"])
return class_(*some_dict["__args__"], **some_dict["__kw__"])
else:
return some_dict

Each time this function is invoked, it checks for the keys that define an encoding of our objects. If the three keys are present, the given function is called with the arguments and keywords. We can use this object hook to parse a JSON object, as follows:

blog_data = json.loads(text, object_hook=blog_decode) 

This will decode a block of text, encoded in a JSON notation, using our blog_decode() function to transform dict into proper Blog and Post objects.

In the next section, we'll take a look at security and the eval() issue.

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

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