How upload Parameters from Json file to dash app

Hi,

Not sure if it is too late, but I have a working example that can help you. In this example, I can upload a plotly figure from json and regenerate the graph in the callback:

"""
Using upload to regenerate plotly figures from JSON
"""
import base64
import json

from dash import Dash, html, dcc, Input, Output, State, callback
from dash.exceptions import PreventUpdate

# Export plot as json
# data = px.scatter(px.data.iris(), x="sepal_length", y="petal_length", color="species").to_json()
# with open('data.json', 'w') as file:
#     file.write(data)

app = Dash(__name__)


app.layout = html.Div(
    [
        dcc.Upload(id="upload-data", children="Upload"),
        html.Div(id="output-data-upload"),
    ]
)


@callback(
    Output("output-data-upload", "children"),
    Input("upload-data", "contents"),
    State("upload-data", "filename"),
)
def on_data_upload(contents, filename):
    if contents is None:
        raise PreventUpdate

    if not filename.endswith(".json"):
        return "Please upload a file with the .json extension"

    content_type, content_string = contents.split(",")
    decoded = base64.b64decode(content_string)
    
    # this is a dict!
    content_dict = json.loads(decoded)

    return dcc.Graph(figure=content_dict)


if __name__ == "__main__":
    app.run_server(debug=True)

Note that up to content_dict the code is quite generic and can be reused for different contexts.

To test it, it is enough to export a go.Figure object to a json file, as done in the code comment.

Hope this helps! :slight_smile:

1 Like