我一直在嘗試在 JSON 格式上換行,但沒有一個不起作用。
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)
在 index.html 中
<!DOCTYPE html>
<html lang="en">
<head>
<title>TEST</title>
<meta charset="utf-8">
</head>
<body>
<p>{{ json_format }}</p>
</body>
</html>
輸出是 {"Author": "Stawa", "Version": "0.1.7"},但我想把它做成
{
"Author": "Stawa",
"Version": "0.1.7"
}
uj5u.com熱心網友回復:
這是因為瀏覽器將您的 JSON 字串解釋為 HTML,并且它不關心換行符。要保留格式,您可以使用 HTML<pre>標記。我使用您的代碼測驗了以下模板,它在兩行中顯示了 JSON。希望它也適用于您的計算機!
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>TEST</title>
<meta charset="utf-8">
</head>
<body>
<pre>{{ json_format }}</pre>
</body>
</html>
輸出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/391890.html
