@@ -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 . clean_to_json_compatible ( value ) )
2323
2424
2525def interpolate_str (template , ** data ):
@@ -252,15 +252,40 @@ def _wrapper(*args, **kwargs):
252252
253253class 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 clean_to_json_compatible (cls , obj ):
270+ if isinstance (obj , pd .DataFrame ):
271+ return {
272+ "__value" : obj .to_dict ("records" ),
273+ "__type" : "DataFrame" ,
274+ }
275+
276+ # Plotly
277+ try :
278+ obj = obj .to_plotly_json ()
279+ except AttributeError :
280+ pass
281+
282+ if isinstance (obj , (list , tuple )):
283+ if obj :
284+ # Must process list recursively even though it may be slow
285+ return [cls .clean_to_json_compatible (v ) for v in obj ]
286+
287+ # Recurse into lists and dictionaries
288+ if isinstance (obj , dict ):
289+ return {k : cls .clean_to_json_compatible (v ) for k , v in obj .items ()}
265290
266- return obj [ "__value" ]
291+ return obj
0 commit comments