Skip to content

Commit 62cfdf9

Browse files
committed
Move serializer to dash core
making possible to accept complex data types (currently Pandas DataFrame) as Layout properties
1 parent 15f233d commit 62cfdf9

1 file changed

Lines changed: 31 additions & 9 deletions

File tree

dash/_utils.py

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ def to_json(value):
1919
# pylint: disable=import-outside-toplevel
2020
from plotly.io.json import to_json_plotly
2121

22-
return to_json_plotly(value)
22+
return to_json_plotly(serializer.serialize_tree(value))
2323

2424

2525
def interpolate_str(template, **data):
@@ -252,15 +252,37 @@ def _wrapper(*args, **kwargs):
252252

253253
class serializer:
254254
@classmethod
255-
def serialize(cls, obj):
256-
if isinstance(obj, pd.DataFrame):
257-
return {"__type": "DataFrame", "__value": obj.to_dict("records")}
255+
def serialize(cls, prop):
256+
if isinstance(prop, pd.DataFrame):
257+
return {"__type": "DataFrame", "__value": prop.to_dict("records")}
258258

259-
return {"__type": "JSON", "__value": obj}
259+
return prop
260260

261261
@classmethod
262-
def unserialize(cls, obj):
263-
if obj["__type"] == "DataFrame":
264-
return pd.DataFrame(obj["__value"])
262+
def unserialize(cls, prop):
263+
if prop["__type"] == "DataFrame":
264+
return pd.DataFrame(prop["__value"])
265+
266+
return prop
267+
268+
@classmethod
269+
def serialize_tree(cls, obj):
270+
if isinstance(obj, pd.DataFrame):
271+
return cls.serialize(obj)
272+
273+
# Plotly
274+
try:
275+
obj = obj.to_plotly_json()
276+
except AttributeError:
277+
pass
278+
279+
if isinstance(obj, (list, tuple)):
280+
if obj:
281+
# Must process list recursively even though it may be slow
282+
return [cls.serialize_tree(v) for v in obj]
283+
284+
# Recurse into lists and dictionaries
285+
if isinstance(obj, dict):
286+
return {k: cls.serialize_tree(v) for k, v in obj.items()}
265287

266-
return obj["__value"]
288+
return obj

0 commit comments

Comments
 (0)