9

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.

sunwarr10r
  • 4,420
  • 8
  • 54
  • 109
  • 1
    Don't call `to_json()` first. `jsonpify()` expects its argument to be a dictionary or list, and it converts it to JSON with the JSONP wrapper. – Barmar Feb 17 '17 at 23:31
  • If I do `jsonpify(dataframe)`I get an error `is not JSON serializable` – sunwarr10r Feb 17 '17 at 23:44
  • 3
    [convert dataframe to list](http://stackoverflow.com/questions/15112234/converting-dataframe-into-a-list) – Barmar Feb 17 '17 at 23:54

2 Answers2

13

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 create the list in a different way. For example like this:

df_list = merged.values.T.tolist() 

Or like this:

df_list = list(df.values.flatten())

Thanks goes to the user @Barmer

sunwarr10r
  • 4,420
  • 8
  • 54
  • 109
2

With this method, columns of dataframe will be the keys and series of dataframe will be the values.

data_dict = dict()
for col in dataframe.columns:
    data_dict[col] = dataframe[col].values.totlist()
return jsonify(data_dict)
Adeel Afzal
  • 191
  • 1
  • 4