Skip to content

Commit d308c81

Browse files
committed
Add numpy type conversion for JSON serialization in query results
1 parent 9f1b6e4 commit d308c81

1 file changed

Lines changed: 23 additions & 2 deletions

File tree

src/vfbquery/ha_api.py

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
from functools import partial
2828

2929
from aiohttp import web
30+
import numpy as np
3031

3132
# ---------------------------------------------------------------------------
3233
# Logging
@@ -132,8 +133,28 @@ def _run_query(short_form, func_name):
132133
fn = getattr(_vfb, func_name)
133134
# AllDatasets is the only query that takes no id argument
134135
if func_name == "get_all_datasets":
135-
return fn(return_dataframe=False)
136-
return fn(short_form, return_dataframe=False)
136+
result = fn(return_dataframe=False)
137+
else:
138+
result = fn(short_form, return_dataframe=False)
139+
140+
# Convert numpy types to Python types for JSON serialization
141+
return _convert_numpy_types(result)
142+
143+
144+
def _convert_numpy_types(obj):
145+
"""Recursively convert numpy types to Python types for JSON serialization."""
146+
if isinstance(obj, dict):
147+
return {k: _convert_numpy_types(v) for k, v in obj.items()}
148+
elif isinstance(obj, list):
149+
return [_convert_numpy_types(item) for item in obj]
150+
elif isinstance(obj, np.integer):
151+
return int(obj)
152+
elif isinstance(obj, np.floating):
153+
return float(obj)
154+
elif isinstance(obj, np.ndarray):
155+
return obj.tolist()
156+
else:
157+
return obj
137158

138159

139160
# ---------------------------------------------------------------------------

0 commit comments

Comments
 (0)