Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flask Python – How do make a newline on json format and return it as html?

I’ve been trying to make newline on JSON Format, but none of it doesn’t work.

from flask import *
import json

app = Flask(__name__)


@app.route("/user/", methods=["GET"])
def user():
    datajson = {"Author": "Stawa", 
                "Version": "0.1.7"}
    json_format = json.dumps(datajson, indent=6)
    return render_template("index.html", json_format=json_format)

in index.html

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>TEST</title>
      <meta charset="utf-8">
   </head>
   <body>
      <p>{{ json_format }}</p>
   </body>
</html>

The out put was {"Author": "Stawa", "Version": "0.1.7"}, but I want to make it as

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
 "Author": "Stawa",
 "Version": "0.1.7"
}

>Solution :

It’s because the browser interprets your JSON string as HTML, and it doesn’t care about newline characters. To preserve formatting, you can use the HTML <pre> tag. I tested the following template with your code, and it displays the JSON on two lines. Hope it works on your computer as well!

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
   <head>
      <title>TEST</title>
      <meta charset="utf-8">
   </head>
   <body>
      <pre>{{ json_format }}</pre>
   </body>
</html>

Output:

Output

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading