JSON Serialization

Learn about the JSON object serialization in Python.

We'll cover the following

The JSON format can serialize a number of commonly used Python object classes, including:

  • None
  • Boolean
  • Float and integer
  • String
  • Lists of compatible objects
  • Dictionaries with string keys and compatible objects as values

The compatible objects can include nested structures. This dictionary-within-list and dictionary-within-dictionary recursion can allow JSON to represent very complex things.

We might consider a theoretical (but invalid) type hint like the following:

JSON = Union[None, bool, int, float, str, List['JSON'], Dict[str, 'JSON']]

This hint isn’t directly supported by mypy, because it involves explicit recursion: the JSON type is defined based on the JSON type. This hint can be a helpful conceptual framework for understanding what we can represent in JSON notation. As a practical matter, we often use Dict[str, Any] to describe JSON objects, ignoring the details of other structures that might be present. We can be a little more specific, though, when we know the expected keys for the dictionary; we’ll expand on this below.

In JSON notation, our data will look like this:

Get hands-on with 1200+ tech skills courses.