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
ExperimentDecoderfrom 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:Only modules registered with the
qiskit_experiments.deserialization_packagesentry point are imported dynamically.Only classes (as determined by Python’s
inspect.isclassfunction) are referenced from the imported modules for further processing.These classes are checked to ensure that they were defined by the registered modules they were loaded from.
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.runand 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 signaturedef __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 adictcontaining other JSON serializable objects).To deserialize this object using the
ExperimentDecoderthe 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.defPython entry point. Inpyproject.tomlthe entry point registration would like this:[project.entry-points."qiskit_experiments.deserialization_packages"] custom-package-name = "custom_package"
where
custom_packageis the Python import module that the custom class is below (the import path before the first.;custom_packagefor classMyClassif it is normally imported asfrom custom_package.subpackage import MyClassfor example). The entry point name,custom-package-namein 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 byExperimentDecoderas 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
ExperimentDecoderis invoked. For scripts and notebook, the scope is named__main__which is registered by default with theqiskit_experiments.deserialization_packagesentry 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
Noneand (‘,’, ‘: ‘) 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 aTypeError).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)