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

标签 python html json flask

有什么方法可以将“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/

相关文章:

python - 帮助,正在将 Python 脚本翻译成 Scala

html - 列出 HTML/CSS 设计方法

json - 如何使用 angular4 将 appsettings.json 中的键值读取到 typescript 文件

html - 如何在 1 行的小屏幕上正确堆叠 col 元素?

javascript - 将 text.json 解析为 jquery.animation?

ios - 将字符串数组转换为 JSON 或 2D 数组 SWIFT

json - 优雅的 Json 在 Spark 中展平

python - PyCharm 警告未解析的引用内置日期时间模块

python - 我的一些 Python 包无法在 OSX 控制台中运行

Python netifaces 模块 Windows 安装