将Python字典转换为JSON并通过Flask发送到HTML。

huangapple go评论64阅读模式
英文:

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:

将Python字典转换为JSON并通过Flask发送到HTML。

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={&#39;a&#39;:True, &#39;b&#39;:False}
a_json=json.dumps(a) # {&quot;a&quot;: true, &quot;b&quot;: false}
return render_template(&quot;index.html&quot;, a_json=a_json)

In HTML:

  &lt;div class=&quot;w3-container&quot;&gt;
      &lt;pre id=&quot;dict&quot;&gt;&lt;/pre&gt;
  &lt;/div&gt;

  &lt;script&gt;
    var data = {{a_json}}
    document.getElementById(&quot;dict&quot;).innerHTML = JSON.stringify(data, undefined, 2);
  &lt;/script&gt;

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:

将Python字典转换为JSON并通过Flask发送到HTML。

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

huangapple
  • 本文由 发表于 2023年5月21日 01:51:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76296619.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定