使用Flask美化显示JSON数据

5

我得到了一个GET请求的响应对象,并使用jsonify()将其转换为JSON格式。当我向模板传递它时,我只会得到一个JSON对象,如下所示:<Response 1366 bytes [200 OK]>

#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?
1个回答

15

使用 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()对象,该对象已经具有适用于JSON响应的正确内容类型标头'application/json',而json.dumps()只会返回一个编码后的字符串,这需要手动添加MIME类型标头。

来源:https://dev59.com/82sz5IYBdhLWcg3wbHLG#13172658


我感觉我们走在了正确的道路上。我执行了 response = json.dumps(response.text, sort_keys=False, indent=2),但整个 JSON 都被显示为一个块,没有换行或缩进。 response = json.dumps(response_json, sort_keys=False, indent=2) 返回 <Response 1366 bytes [200 OK]> is not JSON serializable - Leustad
它仍然显示为文本块。请查看:http://codepen.io/anon/pen/MyMOXJ - Leustad
2
还请查看模板中更新的<pre></pre>标签以进行正确的格式化。 - fulvio
那个<pre></pre>标签会在我用"替换掉那些\"并且去掉开头和结尾的"后有所帮助。 - Leustad
1
找到了我想要做的事情。由于响应的内容类型是 application/json,我已经使用 .json 和响应对象一起使用,如:resp_json = json.dumps(response.json(), sort_keys=True, indent=4) 并将 resp_json 传递给模板。 - Leustad
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接