13

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?

3 Answers 3

31

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})
1
  • JSON is a string! It's used to represent objects. You may even say it's an Object Notation, inspired by JavaScript. Mar 24, 2022 at 17:32
1

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})
0

You can use json in python directly.

# some JSON:
x =  '{ "name":"John", "age":30, "city":"New York"}'

# parse x:
y = json.loads(x)
return y

# the result is a Python dictionary:
print(y["age"])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.