qpanda3_runtime.utils.convert_json_ndarray#

Functions#

ndarray_to_binary_json(arr)

Convert NumPy array to binary JSON format.

binary_json_to_ndarray(json_data)

Restore NumPy array from binary JSON format.

demo_basic_conversion()

Demonstrate basic binary conversion for NumPy arrays.

Module Contents#

qpanda3_runtime.utils.convert_json_ndarray.ndarray_to_binary_json(arr)#

Convert NumPy array to binary JSON format.

This function serializes a NumPy array into a JSON-safe dictionary containing the array’s data, dtype, and shape encoded in base64.

Parameters:

arr (numpy.ndarray) – The NumPy array to be serialized.

Returns:

JSON-safe dictionary with the following keys: - ‘__ndarray__’: True (identifier for ndarray data) - ‘dtype’: string representation of array dtype - ‘shape’: tuple of array dimensions - ‘data’: base64-encoded array bytes

Return type:

dict

Notes

  • The array is converted to bytes using tobytes() method

  • Base64 encoding ensures JSON compatibility

  • Use binary_json_to_ndarray to restore the array

Examples

>>> import numpy as np
>>> arr = np.array([[1, 2], [3, 4]], dtype=np.float32)
>>> json_data = ndarray_to_binary_json(arr)
>>> json_str = json.dumps(json_data)
qpanda3_runtime.utils.convert_json_ndarray.binary_json_to_ndarray(json_data)#

Restore NumPy array from binary JSON format.

This function deserializes a JSON-safe dictionary back into a NumPy array by decoding the base64-encoded data and reconstructing the array with its original dtype and shape.

Parameters:

json_data (dict) – JSON-safe dictionary containing ndarray data. Must have the following keys: - ‘__ndarray__’: True (identifier for ndarray data) - ‘dtype’: string representation of array dtype - ‘shape’: tuple of array dimensions - ‘data’: base64-encoded array bytes

Returns:

Restored NumPy array with original data, dtype, and shape.

Return type:

numpy.ndarray

Raises:
  • ValueError – If the input dictionary does not contain ‘__ndarray__’: True key.

  • TypeError – If the dtype string cannot be parsed or the shape is invalid.

Notes

  • This function is the inverse of ndarray_to_binary_json

  • The dtype string is parsed using numpy’s dtype constructor

  • Missing shape information results in a 1D array

Examples

>>> json_data = {
...     '__ndarray__': True,
...     'dtype': 'float32',
...     'shape': [2, 2],
...     'data': 'AACAPwAAAEAAAEBA'
... }
>>> arr = binary_json_to_ndarray(json_data)
>>> arr.shape
(2, 2)
qpanda3_runtime.utils.convert_json_ndarray.demo_basic_conversion()#

Demonstrate basic binary conversion for NumPy arrays.

This function shows a complete example of converting a NumPy array to JSON format and restoring it back.

Examples

>>> demo_basic_conversion()
=== Basic Binary Conversion Demo ===
Original array:
[[1. 2. 3.]
 [4. 5. 6.]]
Shape: (2, 3), dtype: float32
...