PyMongo and Flask's Jsonify contains escape slashes

后端 未结 1 1825
情话喂你
情话喂你 2021-01-03 07:54

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

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


        
1条回答
  •  时光说笑
    2021-01-03 08:29

    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.

    0 讨论(0)
提交回复
热议问题