Loading a model from json

Suppose I want to save a Bokeh model as json for later use. Following the fact that “the smallest unit of serialization is the document” I do the following:

s = curdoc().to_json_string()
with open("file.json","w") as f:
   f.write(s)

To recover the model, I can do:

with open('document.json') as f:
    d = f.read()
D = Document().from_json_string(d)
f = D.roots[0]
D.clear()
curdoc().add_root(f)

The D.clear() is needed because otherwise you get the error that a model is associated to more than one document.

Is there a more elegant way to do this? The question has been raised before, for example in this stackoverflow post where the answer proposes iterating over all submodels of D.roots[0] and changing the _document property, but clear() seems to work for me.

AFAIK there’s not a better way. No one has really asked about “rehydrating” models in this way (i.e. inside Bokeh server app code) so there’s never been any work put into any API or official support. Might be worth a GitHub issue to discuss.