Skip to content

Commit 571b248

Browse files
authored
Handle ndarray data before JSON serialization (#14)
* Initial test commit * override basefigure to_dict to handle ndarray before json serialization * reformatting * remove redundant condition * Update to use NumpyJSONEncoder instead * linting * remove PlotFigure from scalar_types * linting * linting * undo write override * add indent in json.dumps * remove indent in json.dumps
1 parent 423130a commit 571b248

File tree

4 files changed

+15
-6
lines changed

4 files changed

+15
-6
lines changed

dashipy/dashipy/components/plot.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,7 @@ class Plot(Component):
1414
def to_dict(self) -> dict[str, Any]:
1515
d = super().to_dict()
1616
if self.figure is not None:
17-
# TODO: this is stupid, but if using self.figure.to_dict()
18-
# for plotly.express figures we get
19-
# TypeError: Object of type ndarray is not JSON serializable
20-
d.update(figure=json.loads(self.figure.to_json()))
17+
d.update(figure=self.figure.to_dict())
2118
else:
2219
d.update(figure=None)
2320
return d

dashipy/dashipy/server.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import asyncio
22
import importlib
3+
import json
34
import traceback
45
from typing import Any
56

@@ -12,6 +13,7 @@
1213
from dashipy.context import Context
1314
from dashipy.contribs import Panel
1415
from dashipy.lib import Extension, Contribution
16+
from dashipy.utils import NumpyJSONEncoder
1517

1618
DASHI_CONTEXT_KEY = "dashi.context"
1719
DASHI_EXTENSIONS_KEY = "dashi.extensions"
@@ -117,7 +119,7 @@ def render_layout(
117119
return
118120

119121
self.set_header("Content-Type", "text/json")
120-
self.write({"result": component.to_dict()})
122+
self.write(json.dumps({"result": component.to_dict()}, cls=NumpyJSONEncoder))
121123

122124

123125
class CallbackHandler(DashiHandler):
@@ -172,7 +174,7 @@ def post(self):
172174
)
173175

174176
self.set_header("Content-Type", "text/json")
175-
self.write({"result": change_requests})
177+
self.write(json.dumps({"result": change_requests}, cls=NumpyJSONEncoder))
176178

177179

178180
def print_usage(app, port):

dashipy/dashipy/utils/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
from .json_encoder import NumpyJSONEncoder
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import json
2+
import numpy as np
3+
4+
5+
class NumpyJSONEncoder(json.JSONEncoder):
6+
def default(self, obj):
7+
if isinstance(obj, np.ndarray):
8+
return obj.tolist()
9+
return super().default(obj)

0 commit comments

Comments
 (0)