29
29
import json
30
30
31
31
32
- from plotly .io ._json import config
32
+ from plotly .io ._json import config , clean_to_json_compatible
33
33
from plotly .utils import PlotlyJSONEncoder
34
34
35
35
from _plotly_utils .optional_imports import get_module
36
- from django .utils .encoding import force_text
36
+ from django .utils .encoding import force_str
37
37
from django .utils .functional import Promise
38
38
39
39
40
40
class DjangoPlotlyJSONEncoder (PlotlyJSONEncoder ):
41
41
"""Augment the PlotlyJSONEncoder class with Django delayed processing"""
42
42
def default (self , obj ):
43
43
if isinstance (obj , Promise ):
44
- return force_text (obj )
44
+ return force_str (obj )
45
45
return super ().default (obj )
46
46
47
47
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
+
48
68
def to_json_django_plotly (plotly_object , pretty = False , engine = None ):
49
69
"""
50
70
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):
115
135
opts |= orjson .OPT_INDENT_2
116
136
117
137
# Plotly
138
+
118
139
try :
119
140
plotly_object = plotly_object .to_plotly_json ()
120
141
except AttributeError :
@@ -132,8 +153,10 @@ def to_json_django_plotly(plotly_object, pretty=False, engine=None):
132
153
datetime_allowed = True ,
133
154
modules = modules ,
134
155
)
135
- return orjson .dumps (cleaned , option = opts ).decode ("utf8" )
136
156
157
+ cleaned = promise_clean_to_json_compatible (cleaned )
158
+
159
+ return orjson .dumps (cleaned , option = opts ).decode ("utf8" )
137
160
138
161
import plotly .io .json
139
162
plotly .io .json .to_json_plotly = to_json_django_plotly
0 commit comments