NumpyEncoder is a Python JSON encoder designed to seamlessly handle various NumPy data types, including `ndarray`, `np.number`, `np.datetime64`, and more, which are not natively supported by Python's standard `json` module. It extends `json.JSONEncoder` to provide a plug-and-play solution for serializing data structures containing NumPy objects into JSON strings. The current version is 0.3.2, with releases occurring periodically to maintain compatibility with evolving NumPy versions.
pip install numpyencoderVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to use `NumpyEncoder` to serialize a dictionary containing various NumPy data types (an array, a scalar integer, and a datetime object) into a JSON string. The `cls=NumpyEncoder` argument passed to `json.dumps` ensures that NumPy objects are correctly converted into JSON-serializable Python native types.
Upgrade `numpyencoder` to version 0.3.0 or higher to ensure compatibility with `numpy>=2.0.0`. It is also recommended to review NumPy's 2.0 migration guide for other code adjustments.
Be aware of potential precision loss when serializing floating-point NumPy data. For maximum precision, consider using formats like HDF5 (e.g., `h5py`) or NumPy's native binary format (`np.save`, `np.load`) for storing numerical arrays.
Ensure your NumPy usage adheres to the official NumPy 2.0 migration guide, avoiding deprecated types or patterns, even if `numpyencoder` temporarily supports them for backward compatibility.
Use `NumpyEncoder` when calling `json.dumps()`: `json.dumps(your_data, cls=NumpyEncoder)`. This will convert `np.ndarray` objects to Python lists.
Pass `cls=NumpyEncoder` to `json.dumps()`. `NumpyEncoder` handles these scalar NumPy types by converting them to their equivalent Python native types.
Upgrade `numpyencoder` to version 0.3.0 or higher, which includes specific fixes for NumPy 2.0 compatibility.