cirq.protocols.json_serialization.CirqEncoder

Extend json.JSONEncoder to support Cirq objects.

This supports custom serialization. For details, see the documentation for the SupportsJSON protocol.

In addition to serializing objects that implement the SupportsJSON protocol, this encoder deals with common, basic types:

  • Python complex numbers get saved as a dictionary keyed by 'real' and 'imag'.
  • Numpy ndarrays are converted to lists to use the json module's built-in support for lists.
  • Preliminary support for Sympy objects. Currently only sympy.Symbol. See https://github.com/quantumlib/Cirq/issues/2014

Methods

default

View source

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this::

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return JSONEncoder.default(self, o)

encode

Return a JSON string representation of a Python data structure.

from json.encoder import JSONEncoder
JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'

iterencode

Encode the given object and yield each string representation as available.

For example::

for chunk in JSONEncoder().iterencode(bigobject):
    mysocket.write(chunk)

item_separator ', '
key_separator ': '