Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas to_json returns a string not a json object

I am using the following python code to return a json object:

df_as_json = df.to_json(orient='split')
return jsonify({'status': 'ok', 'json_data': df_as_json})

When I read the object back in javascript:

// response is xhr respose from server
const mydata = response.data
console.log(mydata.constructor.name)
// >Obj
const dfdata = mydata.json_data
console.log(dfdata.constructor.name)
// >String 

Is there a way to send the df_as_json as a json object inside the parent response.data json object?

like image 687
proximacentauri Avatar asked Apr 25 '17 14:04

proximacentauri


2 Answers

There's no such thing as a "json object" in python that's why.to_json returns a string representation of the json object, json in python is essentially the same as a dict, you can use the to_dict method instead.

df_as_json = df.to_dict(orient='split')
return jsonify({'status': 'ok', 'json_data': df_as_json})
like image 65
Taku Avatar answered Oct 12 '22 08:10

Taku


Just return dict and let jsonify convert dict to string.

df_as_json = df.to_dict()
return jsonify({'status': 'ok', 'json_data': df_as_json})
like image 42
Tupis Avatar answered Oct 12 '22 09:10

Tupis