为什么 bson.dumps 转义了我的字典列表 (jsons)

Why is bson.dumps escaping my list of dicts (jsons)

我正在使用 mongo.db 来托管 json 的集合,我使用

将其转换为 json 的列表
    cursor = finder.find_pokemans(db) #this just searches the db for query and works fine
    all_pokemon = [k for k in cursor]

但是当我将列表传递给 jinja2 时,我可以使用以下行将其作为 json 的列表使用:

return render_template('index.html', list_all_pokemon = bson.json_util.dumps(all_pokemon))

我的 html 模板中的这一行(我使用的是内联 js)

var all_pokemon = {{ list_all_pokemon }};

变成

var all_pokemon = [{"_id": {"$oid": "5ca40f82f2463129878bdd93"}, "id": 1, "name": "Bulb

换句话说,它转义了我所有的引号,因此无法用作 json。 我在列表理解行中尝试 jsonify 并在变量传递中尝试 json.dumps,但我收到此错误:

TypeError: Object of type ObjectId is not JSON serializable

关于如何解决这个问题的任何线索?

编辑:我可以使用

class JSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, ObjectId):
            return str(o)
        return json.JSONEncoder.default(self, o)
return render_template('index.html', list_all_pokemon = JSONEncoder().encode(all_pokemon))

它会正常工作,但我想知道为什么我不能像其他场景一样 json.dumps 或 jsonify 以及我是否可以在这里使用这些格式。

{{ list_all_pokemon }} 是一个字符串 - Jinja2 将 HTML-转义任何未标记为 HTML-安全的字符串。

你可以通过这样做来避免这种转义:{{ list_all_pokemon | safe }}...但碰巧的是,Jinja2 自己知道如何做到这一点。这是做你想做的事情的正确方法:

var all_pokemon = {{ all_pokemon | tojson }};

在旧的 Flask 中,您还需要将此标记为安全的,因为它没有为您做这件事 ({{ all_pokemon | tojson | safe }}),但我相信当前的 Flask 不需要您这样做。