Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyMongo and Flask's Jsonify contains escape slashes

I'm trying to make a response using Flask from a Mongodb collection:

@app.route('/stories', methods = ['GET'])
def get_stories():
    stories = db.stories.find()

    json_docs = [json.dumps(doc, default=json_util.default) for doc in stories]

    resp = jsonify(data=json_docs)
    resp.status_code = 200

    return make_response(resp)

This gets all the items and encodes it into a JSON response, but it looks like this:

{
"data": [
   "{\"content\": \"some story here\", \"_id\": {\"$oid\": \"5293c34431e20307544db9cb\"}}", 
   "{\"content\": \"some story here\", \"_id\": {\"$oid\": \"5293c34d31e20307584c3e6e\"}}", 
   "{\"content\": \"some story here\", \"_id\": {\"$oid\": \"5293c57d31e20307a7b40abe\"}}"
   ]
}

Is there a way to encode this using single quotes so it doesn't add in the escape strings? Or is there something I'm overlooking

like image 781
Chris Avatar asked Nov 25 '13 22:11

Chris


People also ask

What is flask-pymongo and how does it work?

Flask applications can leverage PyMongo to access our MongoDB Atlas database. Since Flask is all about improving the developer experience when developing web applications, the community created a widely adopted helper called Flask-PyMongo which is a wrapper around PyMongo, closely integrated with Flask.

What is flask jsonify?

Introduction to Flask jsonify Flask jsonify is defined as a functionality within Python’s capability to convert a json (JavaScript Object Notation) output into a response object with application/json mimetype by wrapping up a dumps () function for adding the enhancements.

How do I update an existing entity in pymongo flask?

Flask-PyMongo provides a helper function for this, the find_one_or_404 () method which will raise a 404 error if the requested resource was not found. To update entries in our database, we may use the update_one () or the replace_one () method to change the value of an existing entity.

What is flask in Python?

Flask is a widely adopted Python framework for building web applications. It allows Python developers to use their preferred language with all of its assets while building scalable and fast-to-start Python web applications.


1 Answers

You are encoding twice:

json_docs = [json.dumps(doc, default=json_util.default) for doc in stories]

resp = jsonify(data=json_docs)

Now each entry in json_docs is a string representing a JSON object.

Remove the json.dumps() call:

resp = jsonify(data=stories)

or use flask.json.dump() with a Response():

resp = Response(json.dumps({'data': stories}, default=json_util.default),
                mimetype='application/json')

This lets you use your json_util.default handler on the cursor objects still.

like image 91
Martijn Pieters Avatar answered Oct 16 '22 09:10

Martijn Pieters