0

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:

enter image description here

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

Rob
  • 518
  • 1
  • 3
  • 18
Vishak Raj
  • 13
  • 5
  • Why don't you put the JSON string directly to the HTML part of the page? There is no need for Javascript at all. – VPfB May 20 '23 at 18:25
  • @VPIB, to show the json data in neat way, I am using the javascript, Do you know any possible way to print the python dict as it is in html with neat way of visualisation... – Vishak Raj May 20 '23 at 19:43

1 Answers1

0

Change the line

var data = {{a_json}}

to

var data = {{ a_json | safe }}

See Passing HTML to template using Flask/Jinja2

Rob
  • 518
  • 1
  • 3
  • 18