Skip to content

Commit 2b31502

Browse files
convert Numpy.Array/Generic for JSON encoding (#1008)
1 parent ede9f60 commit 2b31502

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

CHANGES.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
2323
* Use `@attrs.define` instead of dataclass for factories **breaking change**
2424
* Use `@attrs.define` instead of dataclass for factory extensions **breaking change**
25+
* Handle `numpy` types in JSON/GeoJSON response
2526
2627
### titiler.core
2728

src/titiler/core/titiler/core/resources/responses.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from typing import Any
44

5+
import numpy
56
import simplejson as json
67
from starlette import responses
78

@@ -12,6 +13,16 @@ class XMLResponse(responses.Response):
1213
media_type = "application/xml"
1314

1415

16+
class NumpyEncoder(json.JSONEncoder):
17+
"""Custom JSON Encoder."""
18+
19+
def default(self, obj):
20+
"""Catch numpy types and convert them."""
21+
if isinstance(obj, (numpy.ndarray, numpy.generic)):
22+
return obj.tolist()
23+
return super().default(obj)
24+
25+
1526
class JSONResponse(responses.JSONResponse):
1627
"""Custom JSON Response."""
1728

@@ -27,6 +38,7 @@ def render(self, content: Any) -> bytes:
2738
indent=None,
2839
ignore_nan=True,
2940
separators=(",", ":"),
41+
cls=NumpyEncoder,
3042
).encode("utf-8")
3143

3244

0 commit comments

Comments
 (0)