gpt4 book ai didi

python - 对 html 文件中使用的变量调用 jsonify 渲染不正确

转载 作者:行者123 更新时间:2023-11-30 22:51:01 25 4
gpt4 key购买 nike

有什么方法可以将“jsonify”存储在变量中吗?我不喜欢纯 json 格式的“return jsonify(data)”,但我喜欢缩进,所以我尝试使用渲染的 HTML 模板来美化它。这是我的Python代码:

from flask import Flask, jsonify, render_template
app = Flask(__name__)

@app.route("/")
def return_json():
data = {"One": 1, "Two": 2, "Three": 3, "Letters": ['a', 'b', 'c']}
html_item = jsonify(data)
return render_template("file.html", html_item=html_item)

if __name__ == "__main__":
app.run()

这是我的(此时非常基本的)HTML 文件 (file.html):

<html>
{{ html_item }}
</html>

这是我在浏览器 http://127.0.0.1:5000/ 上得到的输出

<Response 92 bytes [200 OK]> 

如果没有一种方法可以将 jsonify 存储在变量中,有谁知道如何在浏览器上以漂亮的方式显示“数据”?我能弄清楚的是(1)jsonify和(2)“返回数据”,它与jsonify相同,只是没有缩进。

最佳答案

jsonify() 生成一个响应对象,该对象包含 JSON 数据。来自 flask.json.jsonify() documentation :

This function wraps dumps() to add a few enhancements that make life easier. It turns the JSON output into a Response object with the application/json mimetype.

大胆强调我的。当您的路由应该生成 JSON 作为最终结果时,这非常有用,但当您想在模板中使用 JSON 数据时,这就没那么有用了。

您可以使用flask.json.dumps()直接代替:

from flask import json

@app.route("/")
def return_json():
data = {"One": 1, "Two": 2, "Three": 3, "Letters": [a, b, c]}
html_item = json.dumps(data, indent=2, separators=(', ', ': '))
return render_template("file.html", html_item=html_item)

indentseparators 参数是启用 JSONIFY_PRETTYPRINT_REGULARflask.json.jsonify() 使用的参数(默认)并且这不是 AJAX 请求。

或者,在模板中将数据转换为 JSON,使用 tojson filter :

<html>
{{ data|tojson|safe }}
</html>

这假设将 data 传递到模板中,而不是 html_item JSON 字符串。另请注意此处使用 safe 过滤器;这可确保您获得可以使用 JavaScript 代码加载的未转义 JSON 数据,而不是 HTML 转义版本。

您可以将相同的配置传递给该过滤器:

<html>
{{ data|tojson(indent=2, separators=(', ', ': '))|safe }}
</html>

关于python - 对 html 文件中使用的变量调用 jsonify 渲染不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39151472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com