问题描述
我正在使用 |tojson|safe 过滤器将 dict 转换为 JSON:
updateSearchResultsBuffer('{{ Feed['results']|tojson|safe }}');
问题在于 Feed['results']['foo']
处的某些值是带有(未转义的)双引号的字符串(例如 b"a"r
),这会导致令牌无效错误。
我可以通过对 dict 进行一些预处理来解决这个问题:
for item in Feed['results']:
if '"' in item['foo']:
item['foo'] = item['foo'].replace('"','\\"')
我觉得这是不必要的工作,这种逃逸应该自动发生,我在这里遗漏了什么吗?
旁注:在发送到模板之前,我也尝试使用 json.loads(Feed['results'])
,但是引号随后被替换为 "(而不是 \"),这也会导致 JS 无效令牌错误。>
编辑:可重现的错误
app.py
from flask import Flask,render_template
app = Flask(__name__)
@app.route("/",methods=["GET"])
def test():
test_dict_arr = [{'foo': 'b"a"r'}]
return render_template('test.html',test_dict_arr=test_dict_arr)
if __name__ == "__main__":
app.run(host="127.0.0.1",port=8080,debug=True)
模板/test.html
<!DOCTYPE html>
<html>
<body></body>
<script>
window.addEventListener('load',function(){
let parsedJSON = JSON.parse('{{ test_dict_arr|tojson|safe }}');
alert(parsedJSON);
},false);
</script>
<html>
控制台错误:
Uncaught SyntaxError: Unexpected token a in JSON at position 12
at JSON.parse (<anonymous>)
at (index):6
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)