Skip to content

JSONEncoder

Bases: BaseEncoder


Attributes

Name Type Value Doc
ENCODE_ID
(inherited)
int 0 Internal counter to ensure unique encoding ids.

This is set back to 0 if reset_encode_id=True in encode(). Internally, this is only happens in dump(). Nothing bad happens if it is not reset, but the cache ids will not start at 0 as is "standard".

assert_decode

Inherited class method from BaseEncoder.assert_decode().


decode_array staticmethod

decode_array(encoded)

Decode matrix data (JSON version).

Parameters:

Name Type Description Default
json_dict dict

The JSON dictionary containing the matrix.

required

Returns:

Type Description
Any

The decoded matrix.


decode_cached_obj staticmethod

decode_cached_obj(encoded, decode_cache=None)

Decode a cached object reference from JSON format.

This method handles the deserialization of object references that were cached during encoding to avoid duplicate serialization of identical objects. It supports both reference-type caching (where multiple references point to the same object) and copy-type caching (where objects with identical content are stored once and copied).

Parameters:

Name Type Description Default
encoded dict

The JSON dictionary containing the encoded cached object reference. Should have 'encode_type' field set to 'Serializable' and 'cache_type' field indicating the type of cache reference.

required
decode_cache dict

Dictionary mapping cache IDs to decoded objects. Used to resolve object references and handle circular references.

None

Returns:

Type Description
Serializable | DeferredRef

The decoded object. If the referenced object is not yet available in the cache, returns a DeferredRef placeholder that will be resolved later.

Raises:

Type Description
IncorrectDecodableTypeError

If the encoded object is not a valid cached object reference.

DecodableVersionError

If the serialization version is not supported.

RuntimeError

If object references cannot be resolved due to missing source objects.


decode_class staticmethod

decode_class(encoded)

Decode a class/type (JSON version).

Parameters:

Name Type Description Default
json_dict dict

The JSON dictionary containing the class.

required

Returns:

Type Description
type

The decoded class.


decode_dict staticmethod

decode_dict(encoded, decode_cache=None)

Decode an encoded dictionary back to its original form.

Parameters:

Name Type Description Default
encoded Encoded

The encoded dictionary data to be decoded.

required
decode_cache DecodeCache

Cache used to track decoded objects and resolve references.

None

Returns:

Type Description
dict

The decoded dictionary in its original form.

Raises:

Type Description
NotImplementedError

This is an abstract method that must be implemented by subclasses.


decode_function staticmethod

decode_function(encoded)

Decode a callable function (JSON version).

Parameters:

Name Type Description Default
encoded dict

The JSON dictionary containing the function.

required

Returns:

Type Description
callable

The decoded function.


decode_iterable staticmethod

decode_iterable(encoded, decode_cache=None)

Decode an encoded iterable back to its original form.

Parameters:

Name Type Description Default
encoded Encoded

The encoded iterable data to be decoded.

required
decode_cache DecodeCache

Cache used to track decoded objects and resolve references.

None

Returns:

Type Description
EncodableIterables

The decoded iterable in its original form.

Raises:

Type Description
NotImplementedError

This is an abstract method that must be implemented by subclasses.


decode_primitive staticmethod

decode_primitive(encoded)

Decode a primitive value (JSON version).

Parameters:

Name Type Description Default
json_dict dict

The JSON dictionary containing the primitive.

required

Returns:

Type Description
Any

The decoded primitive value.


decode_uncached_obj staticmethod

decode_uncached_obj(encoded, decode_cache=None) -> Serializable | dict

Decode a Serializable object from JSON format.

Deserializes a Serializable object that was not previously cached. This method handles the core deserialization logic for Serializable objects, including attribute reconstruction, circular reference handling, and backwards compatibility with version 0 serialization format.

Parameters:

Name Type Description Default
encoded dict

The JSON dictionary containing the encoded Serializable object. Should have 'encode_type' field set to 'Serializable' and contain keys for each serialized attribute.

required
decode_cache dict

Dictionary mapping cache IDs to decoded objects. Used to handle circular references and object caching during deserialization.

None

Returns:

Type Description
Serializable | dict

The decoded Serializable object of the appropriate class, or the raw dictionary if it's a pygsti object (for backwards compatibility).

Raises:

Type Description
IncorrectDecodableTypeError

If the encoded object is not a valid Serializable object.

DecodableVersionError

If the serialization version is not supported.

ImportError

If the class cannot be imported from the specified module.


encode_array staticmethod

encode_array(to_encode)

Encode NumPy arrays and SciPy sparse matrices to JSON format.

Serializes array data to JSON-compatible structures. Handles both dense and sparse matrices, with special handling for complex numbers and type preservation.

Parameters:

Name Type Description Default
to_encode EncodableArrays

The array to encode. Can be a NumPy array (np.ndarray) or SciPy sparse matrix.

required

Returns:

Type Description
dict

The JSON dictionary containing the encoded array data.

Raises:

Type Description
ValueError

If the array type is not supported.


encode_cached_obj staticmethod

encode_cached_obj(cache_id, cache_type='reference', reference_cache_id=None, source_cache_id=None)

Encode a cached object reference in JSON format.

This method creates a reference to an object that has already been serialized, avoiding duplicate storage of identical objects. Used for implementing object caching during serialization to improve efficiency and handle circular references.

Parameters:

Name Type Description Default
cache_id int

The cache ID for this reference.

required
cache_type str

Type of cache reference, either 'reference' (multiple references to same object) or 'copy' (copy of an existing object). Default is 'reference'.

'reference'
reference_cache_id int

For copy-type caching, the cache ID of the reference object.

None
source_cache_id int

For copy-type caching, the cache ID to assign to the copied object.

None

Returns:

Type Description
dict

The JSON dictionary containing the encoded cached object reference.


encode_class staticmethod

encode_class(to_encode)

Encode a class/type (JSON version).

Parameters:

Name Type Description Default
to_encode type

The class/type to encode.

required

Returns:

Type Description
dict

The JSON dictionary with the encoded class.


encode_dict staticmethod

encode_dict(to_encode, encode_cache=None, ignore_no_serialize_flags=False)

Encode a dictionary (JSON version).

Parameters:

Name Type Description Default
d dict

The dictionary to encode.

required
encode_cache dict

Dictionary mapping object hashes to serialization IDs.

None
ignore_no_serialize_flags bool

Whether to ignore serialization flags.

False

Returns:

Type Description
dict

The JSON dictionary with the encoded dictionary.


encode_function staticmethod

encode_function(to_encode)

Encode a callable function (JSON version).

Parameters:

Name Type Description Default
func callable

The function to encode.

required

Returns:

Type Description
dict

The JSON dictionary with the encoded function.


encode_iterable staticmethod

encode_iterable(to_encode, encode_cache=None, ignore_no_serialize_flags=False)

Encode an iterable into a serializable format.

Parameters:

Name Type Description Default
to_encode EncodableIterables

The iterable to be encoded.

required
encode_cache EncodeCache

Cache used to track encoded objects and avoid duplication.

None
ignore_no_serialize_flags bool

If True, ignores any no-serialize flags on objects. Default is False.

False

Returns:

Type Description
Encoded

The encoded representation of the iterable.

Raises:

Type Description
NotImplementedError

This is an abstract method that must be implemented by subclasses.


encode_primitive staticmethod

encode_primitive(to_encode)

Encode a primitive value (JSON version).

Emits bare bools/ints/floats/None directly, since JSON's own type system already distinguishes them and decode_primitive's "not a dict" case already treats a bare value as a primitive. Strings stay wrapped: decode_function's legacy heuristic (needed for real SERIALIZATION_VERSION 0 files, which recorded function source as unwrapped strings) can't tell a bare string containing "def " apart from real function source stored deliberately as a plain string attribute elsewhere in this codebase -- keeping strings wrapped avoids that collision, since a dict never matches that heuristic.

Numpy scalars keep their dtype, written in a wrapper with a dtype field, and Python complex values are tagged cast_to: "complex". A numpy scalar that can't be stored exactly (a timedelta64, or a floating or complex type wider than 64 or 128 bits) raises ValueError.

Parameters:

Name Type Description Default
to_encode Any

The primitive value to encode.

required

Returns:

Type Description
Any

The primitive value directly (for JSON), except strings, numpy scalars and complex, which use the {"encode_type": "primitive", ...} wrapper.


encode_uncached_obj staticmethod

encode_uncached_obj(to_encode, encode_cache=None, ignore_no_serialize_flags=False)

Encode an object that has not been previously cached.

Parameters:

Name Type Description Default
to_encode Serializable

The object to be encoded.

required
encode_cache EncodeCache

Cache used to track encoded objects and avoid duplication.

None
ignore_no_serialize_flags bool

If True, ignores any no-serialize flags on objects. Default is False.

False

Returns:

Type Description
Encoded

The encoded representation of the object.

Raises:

Type Description
NotImplementedError

This is an abstract method that must be implemented by subclasses.