Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to format the JSON?

I am trying to output json data from a pandas dataframe directly into dcc.store (plotly-dash component), which is the output with id ‘intermediate-value’. So, I made a dictionary, and I dumped the JSON. I keep getting this error:

Expected type: (<class 'tuple'>, <class 'list'>)
Received value of type <class 'str'>

I understand it says I am passing it a string, and that I should be passing it a tuple (or?) a list. What I am unsure of is how to edit my code to match the data structure it desires. Could anyone provide insight, I included my function in question below:

@app.callback(
    [
        Output('intermediate-value', 'data')
    ],
    [
        Input("keyword-selection", "value"),
        Input("status-selection", "value")
    ]
)
def color_map(keyword_selected, status_selected):
    local_df = df_xy_coord[df_xy_coord["active"] == status_selected].copy() if status_selected != "All" else df_xy_coord

    color_index = 0
    for keyword in keyword_selected:
        local_df.loc[local_df["keyword"] == keyword, 'color'] = colors[color_index]
        color_index += 1

    color_dictionary = dict( zip( local_df.keyword, local_df.color ) )
    return( json.dumps(color_dictionary, indent = 4) )

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To return a tuple in Python (the comma is necessary for Python to parse it as a tuple of size 1):

return (color_dictionary,  )

To return a list in Python:

return [color_dictionary]

json.dumps serializes an object (e.g. a dict) to a JSON formatted str.
You can serialise your dict into a JSON string first and then return it inside a tuple or list following the examples above.
See docs for json.dumps here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading