Skip to content

Commit

Permalink
convert Numpy.Array/Generic for JSON encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
vincentsarago committed Oct 25, 2024
1 parent ede9f60 commit 21ef542
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

* Use `@attrs.define` instead of dataclass for factories **breaking change**
* Use `@attrs.define` instead of dataclass for factory extensions **breaking change**
* Handle `numpy` types in JSON/GeoJSON response

### titiler.core

Expand Down
12 changes: 12 additions & 0 deletions src/titiler/core/titiler/core/resources/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from typing import Any

import numpy
import simplejson as json
from starlette import responses

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


class NumpyEncoder(json.JSONEncoder):
"""Custom JSON Encoder."""

def default(self, obj):
"""Catch numpy types and convert them."""
if isinstance(obj, (numpy.ndarray, numpy.generic)):
return obj.tolist()
return super().default(obj)


class JSONResponse(responses.JSONResponse):
"""Custom JSON Response."""

Expand All @@ -27,6 +38,7 @@ def render(self, content: Any) -> bytes:
indent=None,
ignore_nan=True,
separators=(",", ":"),
cls=NumpyEncoder,
).encode("utf-8")


Expand Down

0 comments on commit 21ef542

Please sign in to comment.