Return Pandas dataframe as JSONP response in Python Flask

纵饮孤独 提交于 2019-12-07 01:15:15

问题


I want to return data as JSONPresponse in Flask.

The data comes from a Pandas dataframe and I can return it as JSON with the following line:

json_data = dataframe.to_json(orient='values')
return json_data

Works fine and I get the data, which looks like this:

[[1487310600000,1038,1042,1038,1038,-2.243,6.8933],[1487310900000,1042,1042,1038,1038,-1.3626,4.3058],[1487311200000,1042,1042,1038,1038,-1.4631,17.8684]]

But I need it as JSONP, so I use the following code:

from flask_jsonpify import jsonpify
json_data = dataframe.to_json(orient='values')
return jsonpify(json_data)

And it gives me the data, but with double quotes:

"[[1487310600000,1038,1042,1038,1038,-2.243,6.8933],[1487310900000,1042,1042,1038,1038,-1.3626,4.3058],[1487311200000,1042,1042,1038,1038,-1.4631,17.8684]]"

How can I get the JSONP response in Flask without double quotes? Many thanks in advance.


回答1:


This is my solution to convert a Pandas dataframe to JSONP an return it in Flask:

from flask_jsonpify import jsonpify
df_list = df.values.tolist()
JSONP_data = jsonpify(df_list)
return JSONP_data

Depending on how you need the dataframe converted, you might need to make the list in a different way as me, e.g. like this df_list = merged.values.T.tolist() or like this df_list = list(df.values.flatten()) etc.

Thanks goes to the user @Barmer



来源:https://stackoverflow.com/questions/42309133/return-pandas-dataframe-as-jsonp-response-in-python-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!