ExperimentEncoder

class ExperimentEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

JSON Encoder for Qiskit Experiments.

Warning

It is recommended only to deserialize data with ExperimentDecoder from trusted sources. For custom classes, the deserialization procedure involves dynamic execution of code based on the content of the serialized data. The deserialization code includes some safeguards:

  1. Only modules registered with the qiskit_experiments.deserialization_packages entry point are imported dynamically.

  2. Only classes (as determined by Python’s inspect.isclass function) are referenced from the imported modules for further processing.

  3. These classes are checked to ensure that they were defined by the registered modules they were loaded from.

  4. For the referenced classes, only the __json_decode__ method is called with the serialized data.

Even with these safeguards, loading a payload involves instantiating registered classes with arbitrary inputs. These classes were not written assuming malicious input.

Note that versions of Qiskit Experiments older than 0.14 could load arbitrary functions like subprocess.run and pass them data from the deserialization payload.

This class extends the default Python JSONEncoder by including built-in support for

  • complex numbers, inf and NaN floats, sets, and dataclasses.

  • NumPy ndarrays and SciPy sparse matrices.

  • Qiskit QuantumCircuit.

  • Any class that implements a __json_encode__ method

Custom classes can be serialized by this encoder by implementing a __json_encode__ method. The serialization procedure is as follows:

The __json_encode__ method should have signature

def __json_encode__(self) -> Any:
    # return a JSON serializable object value

The value returned by __json_encode__ must be an object that can be serialized by the JSON encoder (for example a dict containing other JSON serializable objects).

To deserialize this object using the ExperimentDecoder the class must also provide a __json_decode__ class method that can convert the value returned by __json_encode__ back to the object. This method should have signature

@classmethod
def __json_decode__(cls, value: Any) -> Self:
    # recover the object from the `value` returned by __json_encode__

Additionally, the custom class’s package metadata must register the top level import package as a qiskit_experiments.def Python entry point. In pyproject.toml the entry point registration would like this:

[project.entry-points."qiskit_experiments.deserialization_packages"]
custom-package-name = "custom_package"

where custom_package is the Python import module that the custom class is below (the import path before the first .; custom_package for class MyClass if it is normally imported as from custom_package.subpackage import MyClass for example). The entry point name, custom-package-name in the example, is not used and can be set to any descriptive name.

If the object has no __json_encode__ method and all other special cases (numpy arrays, Qiskit quantum info classes, etc.) do not apply, the object is serialized as though __json_encode__ returned an empty dict. Without a __json_decode__ method, the object will be loaded by ExperimentDecoder as a dictionary containing the name of the object’s class and module. This incomplete loading of the object may lead to other code execution problems.

Note

Serialization of custom classes works for user-defined classes in Python scripts, notebooks, or third party modules. Note however that these will only be able to be de-serialized if that class can be imported form the same scope at the time the ExperimentDecoder is invoked. For scripts and notebook, the scope is named __main__ which is registered by default with the qiskit_experiments.deserialization_packages entry point.

Constructor for JSONEncoder, with sensible defaults.

If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float, bool or None. If skipkeys is True, such items are simply skipped.

If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII and non-printable characters escaped. If ensure_ascii is false, the output can contain non-ASCII and non-printable characters.

If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an RecursionError). Otherwise, no such check takes place.

If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.

If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (’, ‘, ‘: ‘) if indent is None and (‘,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘,’, ‘:’) to eliminate whitespace.

If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError.

Attributes

item_separator = ', '
key_separator = ': '

Methods

default(obj)[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 super().default(o)
Return type:

Any

encode(o)

Return a JSON string representation of a Python data structure.

>>> from json.encoder import JSONEncoder
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
iterencode(o, _one_shot=False)

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

For example:

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