Dan Dan - 1 month ago 16
JSON Question

Confused by Python returning JSON as string instead of literal

I've done some coding in RoR, and in Rails, when I return a JSON object via an API call, it returns as

{ "id" : "1", "name" : "Dan" }
.

However in Python (with Flask and Flask-SQLAlchemy), when I return a JSON object via json.dumps or jsonpickle.encode it is returned as

"{ \"id\" : \"1\", \"name\": \"Dan\" }"
which seems very unwieldily as it can't easily be parsed on the other end (by an iOS app in this case - Obj-C).

What am I missing here, and what should I do to return it as a JSON literal, rather than a JSON string?

This is what my code looks like:

people = models.UserRelationships.query.filter_by(user_id=user_id, active=ACTIVE_RECORD)
friends = people.filter_by(friends=YES)

json_object = jsonpickle.encode(friends.first().as_dict(), unpicklable=False, keys=True)
print(json_object) # this prints here, i.e. { "id" : "1", "name" : "Dan" }

return json_object # this returns "{ \"id\" : \"1\", \"name\": \"Dan\" }" to the browser

Answer

You should be using flask.jsonify, which will not only encode correctly, but also set the content-type headers accordingly.

people = models.UserRelationships.query.filter_by(user_id=user_id, active=ACTIVE_RECORD)
friends = people.filter_by(friends=YES)

return jsonify(friends.first().as_dict())