PyMongo和Flask的Jsonify包含转义斜线

编程入门 行业动态 更新时间:2024-10-23 07:37:25
本文介绍了PyMongo和Flask的Jsonify包含转义斜线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

$ b

@ app.route('/ stories)我试图用Mongodb集合中的Flask做出响应。 ',methods = ['GET']) def get_stories(): stories = db.stories.find() $ b $ 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)

获取所有项目并将其编码为JSON响应,但看起来像这样:

{data:[{\content \:\ \_id \:{\$ oid \:\5293c34431e20307544db9cb \}},{\content \:\一些故事在这里,\_id \:{\$ oid \:\5293c34d31e20307584c3e6e\}},{\content \: \这里有些故事,\_id \:{\$ oid \:\5293c5 7d31e20307a7b40abe\}}}

有没有办法编码这个使用单引号,所以它不会在转义字符串中添加?或者是有我忽略的东西

解决方案

您正在编码两次:

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

现在在 json_docs 是一个表示JSON对象的字符串。

删除 json.dumps()调用:

resp = jsonify(data = stories)

或使用 flask.json.dump()与 Response():

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

这样可以使用 json_util。游标对象上的默认处理程序仍然存在。

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

解决方案

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.

更多推荐

PyMongo和Flask的Jsonify包含转义斜线

本文发布于:2023-11-26 07:02:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633112.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:斜线   PyMongo   Flask   Jsonify

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!