英文:
python dict to json and sending to HTML using Flask
问题
I need to print a big python dictionary in HTML with neat format to read using Flask.
Lets take this dict
as example:
a = {'a': True, 'b': False}
a_json = json.dumps(a) # {"a": true, "b": false}
return render_template("index.html", a_json=a_json)
In HTML:
<div class="w3-container">
<pre id="dict"></pre>
</div>
<script>
var data = {{ a_json }}
document.getElementById("dict").innerHTML = JSON.stringify(data, undefined, 2);
</script>
This does not showing the data, when I checked the open the "view page source", I see that the JSON data is different, and there are extra characters are available like this:
When, I give the JSON data directly in the script
tag, I got the dictionary visible in the web page.
How to make this JSON data visible in the web page (or)
How to make the dict
visible in html in neat format?
Thanks
英文:
I need to print a big python dictionary in HTML with neat format to read using Flask.
Lets take this dict
as example:
a={'a':True, 'b':False}
a_json=json.dumps(a) # {"a": true, "b": false}
return render_template("index.html", a_json=a_json)
In HTML:
<div class="w3-container">
<pre id="dict"></pre>
</div>
<script>
var data = {{a_json}}
document.getElementById("dict").innerHTML = JSON.stringify(data, undefined, 2);
</script>
This does not showing the data, when I checked the open the "view page source", I see that the JSON data is different, and there are extra characters are available like this:
When, I give the JSON data directly in the script
tag, I got the dictionary visible in the web page.
How to make this JSON data visible in the web page (or)
How to make the dict
visible in html in neat format?
Thanks
答案1
得分: 0
Change the line
var data = {{ a_json }}
to
var data = {{ a_json | safe }}
查看 https://stackoverflow.com/questions/3206344/passing-html-to-template-using-flask-jinja2
英文:
Change the line
var data = {{a_json}}
to
var data = {{ a_json | safe }}
See https://stackoverflow.com/questions/3206344/passing-html-to-template-using-flask-jinja2
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论