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.
Install & Compatibility
Where this runs
tested against v0.3.2 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.920 runs
installs and imports cleanly · install 0.0s · import 0.268s · 90.1MB
glibcpy 3.10–3.920 runs
installs and imports cleanly · install 3.7s · import 0.273s · 86MB
90MB installed
● package 90MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
from numpyencoder import NumpyEncoder
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.
import json
import numpy as np
from numpyencoder import NumpyEncoder
# Example with a NumPy array and scalar
numpy_data = {
'array_field': np.array([0, 1.5, 2, 3]),
'scalar_field': np.int64(123),
'datetime_field': np.datetime64('2023-01-01T12:00:00')
}
# Serialize the data using NumpyEncoder
json_output = json.dumps(numpy_data, cls=NumpyEncoder, indent=2)
print(json_output)
# The output will convert numpy types to native Python types (lists, int, string for datetime)
expected_output_fragment = '"array_field": [
0.0,
1.5,
2.0,
3.0
],
"scalar_field": 123,
"datetime_field": "2023-01-01T12:00:00"'
Upgrade
Version history
Breaking-change detection hasn't run for this library yet.
Audit
Security & dependencies
CVE tracking and dependency tree are planned for a later release.