【问题标题】:Pretty Display JSON data from with Flask [duplicate]使用 Flask 漂亮地显示 JSON 数据 [重复]
【发布时间】:2016-09-17 02:43:31
【问题描述】:

由于GET 请求,我得到了一个响应对象,我已将其转换为JSONjsonify()。当我将它传递给模板时,我得到的只是一个 JSON 对象,例如:<Response 1366 bytes [200 OK]> this。

#request.py
...
response = requests.get('http://www.example.com')
response_json = jsonify(all=response.text)

return render_template(
    'results.html',
    form=ReqForm(request.form),
    response=response_json,
    date=datetime.datetime.now()
)

和模板..

#results.html
...
<div class="results">
    {{ response }} # --> gives <Response 1366 bytes [200 OK]>
</div>
...

如何在模板中漂亮地显示这个 JSON?

【问题讨论】:

    标签: python json flask


    【解决方案1】:

    使用json.dumps

    response = json.dumps(response.text, sort_keys = False, indent = 2)
    

    或者让它更漂亮

    response = json.dumps(response.text, sort_keys = True, indent = 4, separators = (',', ': '))
    

    模板

    #results.html
    ...
    <div class="results">
        <pre>{{ response }}</pre>
    </div>
    ...
    

    flask 中的 jsonify() 函数返回 flask.Response() 对象,该对象已经具有适当的内容类型标头 'application/json' 用于 json 响应,而 json.dumps() 将只返回一个编码字符串,这需要手动添加mime 类型标题。

    来源:https://stackoverflow.com/a/13172658/264802

    【讨论】:

    • 我觉得我们走在正确的道路上。我做了response = json.dumps(response.text, sort_keys=False, indent=2),但整个 json 显示为块。没有换行符或缩进。 response = json.dumps(response_json, sort_keys=False, indent=2) 返回&lt;Response 1366 bytes [200 OK]&gt; is not JSON serializable
    • 它仍然显示为一个文本块。看看吧:codepen.io/anon/pen/MyMOXJ
    • 另请参阅模板中更新的
       标记以了解正确的格式。
    • 当我用" 替换那些\" 并从头到尾去掉" 时,&lt;pre&gt;&lt;/pre&gt; 标签会有所帮助
    • 找到了我想做的事。由于响应的内容类型是application/json,我将.json 与响应对象一起使用,例如:resp_json = json.dumps(response.json(), sort_keys=True, indent=4) 并将resp_json 传递给模板。
    猜你喜欢
    • 2020-07-23
    • 2019-06-06
    • 2018-12-19
    • 2017-05-01
    • 2015-07-03
    • 2015-08-26
    相关资源
    最近更新 更多