I'm using mongo.db to host a collection of jsons, which I turned into a list of jsons using
cursor = finder.find_pokemans(db) #this just searches the db for query and works fine
all_pokemon = [k for k in cursor]
But when I pass the list to jinja2 so I can work with it in as a list of jsons using the following line:
return render_template('index.html', list_all_pokemon = bson.json_util.dumps(all_pokemon))
this line in my html template (I'm using inline js)
var all_pokemon = {{ list_all_pokemon }};
turns into
var all_pokemon = [{"_id": {"$oid": "5ca40f82f2463129878bdd93"}, "id": 1, "name": "Bulb
In other words, it escapes all my quotes so it's unusuable as a json. I tried jsonifying in the list comprehension line and json.dumps in the variable passing, but I get this error:
TypeError: Object of type ObjectId is not JSON serializable
Any clues as to how to fix this?
EDIT: I can use
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))
and it will work fine, but I was wondering why I can't json.dumps or jsonify like other scenarios and whether I can use those formats instead here.
{{ list_all_pokemon }}
is a string - Jinja2 will HTML-escape any string that is not marked as HTML-safe.
You can avoid this escaping by doing so: {{ list_all_pokemon | safe }}
... But as it happens, Jinja2 knows how to do it by itself. This is the proper way to do what you want:
var all_pokemon = {{ all_pokemon | tojson }};
In the old Flask you were also required to mark this as safe, as it didn't do it for you ({{ all_pokemon | tojson | safe }}
) but I believe current Flask does not require you to.