2929import json
3030
3131
32- from plotly .io ._json import config
32+ from plotly .io ._json import config , clean_to_json_compatible
3333from plotly .utils import PlotlyJSONEncoder
3434
3535from _plotly_utils .optional_imports import get_module
36- from django .utils .encoding import force_text
36+ from django .utils .encoding import force_str
3737from django .utils .functional import Promise
3838
3939
4040class DjangoPlotlyJSONEncoder (PlotlyJSONEncoder ):
4141 """Augment the PlotlyJSONEncoder class with Django delayed processing"""
4242 def default (self , obj ):
4343 if isinstance (obj , Promise ):
44- return force_text (obj )
44+ return force_str (obj )
4545 return super ().default (obj )
4646
4747
48+ def promise_clean_to_json_compatible (obj ):
49+
50+ if isinstance (obj , dict ):
51+ return {promise_clean_to_json_compatible (k ): promise_clean_to_json_compatible (v ) for k , v in obj .items ()}
52+
53+ if isinstance (obj , (list , tuple )):
54+ if obj :
55+ return [promise_clean_to_json_compatible (v ) for v in obj ]
56+
57+ if isinstance (obj , Promise ):
58+ return force_str (obj )
59+
60+ #try:
61+ # return obj.to_plotly_json()
62+ #except AttributeError:
63+ # pass
64+
65+ return obj
66+
67+
4868def to_json_django_plotly (plotly_object , pretty = False , engine = None ):
4969 """
5070 Convert a plotly/Dash object to a JSON string representation
@@ -115,6 +135,7 @@ def to_json_django_plotly(plotly_object, pretty=False, engine=None):
115135 opts |= orjson .OPT_INDENT_2
116136
117137 # Plotly
138+
118139 try :
119140 plotly_object = plotly_object .to_plotly_json ()
120141 except AttributeError :
@@ -132,8 +153,10 @@ def to_json_django_plotly(plotly_object, pretty=False, engine=None):
132153 datetime_allowed = True ,
133154 modules = modules ,
134155 )
135- return orjson .dumps (cleaned , option = opts ).decode ("utf8" )
136156
157+ cleaned = promise_clean_to_json_compatible (cleaned )
158+
159+ return orjson .dumps (cleaned , option = opts ).decode ("utf8" )
137160
138161import plotly .io .json
139162plotly .io .json .to_json_plotly = to_json_django_plotly
0 commit comments