SteveS
SteveS

Reputation: 4040

How to display dictionary with dataframes on a localhost (using Flask and Python)?

I have the following dict:

{'id': 1, 'df': pd.DataFrame({'id': [1,2,3], 'col1': ['kuku', 'dudu', 'lulu'], 'col2': [8,9,10]}), 'df_size': 3}

When I am trying to print it using Flask app on my localhost:5000 it returns an error:

@app.route("/showDict")
def show_dict():
    import pandas as pd
    return {'id': 1, 'df': pd.DataFrame({'id': [1,2,3], 'col1': ['kuku', 'dudu', 'lulu'], 'col2': [8,9,10]}), 'df_size': 3}

raise TypeError(f'Object of type {o.class.name} ' TypeError: Object of type DataFrame is not JSON serializable

Please advise how can I print such a dict via Flask app?

Upvotes: 0

Views: 172

Answers (1)

Eric CHEUNG
Eric CHEUNG

Reputation: 11

You should convert your dict to json before you return it, try this:

@app.route("/showDict")
def show_dict():
    import pandas as pd
    df = pd.DataFrame({'id': [1, 2, 3], 'col1': ['kuku', 'dudu', 'lulu'], 'col2': [8, 9, 10]}).to_json()
    return {'id': 1, 'df': df, 'df_size': 3}

you can see this article, I hope this can help you: https://www.geeksforgeeks.org/json-dumps-in-python/

Upvotes: 1

Related Questions