I passed a result to javascript in json. But when I use var myList = {{ pass_tmp|tojson|safe }}
to transform the result to json, there is a bug said that TypeError: ObjectId('') is not JSON serializable
. I have read this question TypeError: ObjectId('') is not JSON serializable .But the situation in this question is a little different from mine.I have to convert this to json in a flask template instead of a python file.And I have to use the command var myList = {{ pass_tmp|tojson|safe }}
to pass this from html to javascript.So I wonder if I can convert ObjectId
to String
? Here is my Flask app code:
@app.route('/details/', methods=['GET'])
def details():
if request.method == 'GET':
mongoClient = pymongo.MongoClient('localhost', 27017)
name = session['name']
print name
db = mongoClient[name]
results = db[name].find()
json_results= []
for result in results:
json_results.append(result)
# json_tmp = toJson(json_results)
return render_template('details.html', pass_tmp=json_results)
Here is my template(javascript) code:
var myList = {{ pass_tmp|tojson|safe }}
// Builds the HTML Table out of myList json data from Ivy restful service.
function buildHtmlTable() {
var columns = addAllColumnHeaders(myList);
for (var i = 0 ; i < myList.length ; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0 ; colIndex < columns.length ; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) { cellValue = ""; }
row$.append($('<td/>').html(cellValue));
}
$("#excelDataTable").append(row$);
}
}
So does anyone has any good suggestions to solve this problem?
I have solved this problem by just pass json to template instead of results.
@app.route('/details/', methods=['GET'])
def details():
if request.method == 'GET':
mongoClient = pymongo.MongoClient('localhost', 27017)
name = session['name']
print name
db = mongoClient[name]
results = db[name].find()
json_results= []
for result in results:
json_results.append(result)
json_tmp = toJson(json_results)
return render_template('details.html', pass_tmp=json_tmp)
And use this in template: var myList = {{ pass_tmp|safe }}
instead of var myList = {{pass_tmp|tojson|safe}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.