Home > Mobile >  Flask Python - How do make a newline on json format and return it as html?
Flask Python - How do make a newline on json format and return it as html?

Time:12-25

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

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

CodePudding user response:

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

  • Related