以简洁的方式显示从 Flask 返回的 JSON [英] Display JSON returned from Flask in a neat way

查看:11
本文介绍了以简洁的方式显示从 Flask 返回的 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Flask 创建 API 并具有以下代码:

I'm creating an API using Flask and have the following code:

@app.route('/<major>/')
def major_res(major):
    course_list = list(client.db.course_col.find({"major": (major.encode("utf8", "ignore").upper())}))
    return json.dumps(course_list, sort_keys=True, indent=4, default=json_util.default)

在浏览器中查看/csci/时,输出如下:

When viewing /csci/ in the browser, the output looks like this:

[{ "course": "CSCI052", "description": "Fundamentals of Computer Science. A solid foundation in functional programming, procedural and data abstraction, recursion and problem-solving. Applications to key areas of computer science, including algorithms and complexity, computer architecture and organization, programming languages, finite automata and computability. This course serves the same role as HM 60 as a prerequisite for upper-division computer science courses at any of the Claremont Colleges. Prerequisite: 51.", "instructor": "Bull, Everett L.,, Jr.", "name": " Fundamentals of Computer Science", "number": 52, "school": "PO" }]

如何返回这个字典,使每个键和值都在自己的行上?

How do I return this dictionary so that each key and value are on their own line?

推荐答案

Flask 提供 jsonify() 方便:

Flask provides jsonify() as a convenience:

from flask import jsonify

@app.route("/<major>/")
def major_res(major):
    course_list = list(client.db.course_col.find({"major": major.upper()}))
    return flask.jsonify(**course_list)

这将返回 jsonify 的参数作为 JSON 表示,并且与您的代码不同,将发送正确的 Content-Type 标头:application/json.请注意文档对格式的说明:

This will return the args of jsonify as a JSON representation, and, unlike your code, will send the proper Content-Type header: application/json. Take note of what the docs say about the format:

如果 JSONIFY_PRETTYPRINT_REGULAR 配置参数设置为 True 或 Flask 应用程序在调试模式下运行,该函数的响应将被打印出来.压缩(不漂亮)格式目前意味着分隔符后没有缩进和空格.

This function's response will be pretty printed if the JSONIFY_PRETTYPRINT_REGULAR config parameter is set to True or the Flask app is running in debug mode. Compressed (not pretty) formatting currently means no indents and no spaces after separators.

当不在调试模式下时,响应将收到非漂亮打印的 JSON.这应该不是问题,因为用于 JavaScript 消费的 JSON 不需要格式化(这只是要通过网络发送的额外数据),并且大多数工具格式自己接收 JSON.

Responses will receive non-pretty-printed JSON when not in debug mode. This shouldn't be a problem since JSON for JavaScript consumption shouldn't need to be formatted (that's just extra data to be sent over the wire), and most tools format received JSON on their own.

如果您仍想使用 json.dumps(),您可以通过返回一个 Responsecurrent_app.response_class().

If you'd like to still use json.dumps(), you can send the proper mimetype by returning a Response with current_app.response_class().

from flask import json, current_app

@app.route("/<major>/")
def major_res(major):
    course_list = list(client.db.course_col.find({"major": major.upper() }))
    return current_app.response_class(json.dumps(course_list), mimetype="application/json")

有关差异的更多信息:

在 Flask 1.0 之前,JSON 处理有些不同.jsonify 会尝试检测请求是否是 AJAX,如果不是,则返回打印得很漂亮;这被删除了,因为它不可靠.jsonify 仅允许 dicts 作为 安全原因的顶级对象;这不再适用于现代浏览器.

Prior to Flask 1.0, JSON handling was somewhat different. jsonify would try to detect whether a request was AJAX and return pretty printed if it was not; this was removed because it was unreliable. jsonify only allowed dicts as the top-level object for security reasons; this is no longer applicable in modern browsers.

这篇关于以简洁的方式显示从 Flask 返回的 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆