Python 以简洁的方式显示从 Flask 返回的 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16908943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display JSON returned from Flask in a neat way
提问by Aloke Desai
I'm creating an API using Flask and have the following code:
我正在使用 Flask 创建 API 并具有以下代码:
@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)
When viewing /csci/in the browser, the output looks like this:
在浏览/csci/器中查看时,输出如下所示:
[{ "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?
我如何返回这本字典,以便每个键和值都在自己的行上?
采纳答案by Bailey Parker
Flask provides jsonify()as a convenience:
Flask 提供jsonify()了便利:
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)
This will return the args of jsonifyas a JSON representation, and, unlike your code, will send the proper Content-Typeheader: application/json. Take note of what the docs say about the format:
这将返回 argsjsonify作为 JSON 表示,并且与您的代码不同,将发送正确的Content-Type标头:application/json。请注意文档对格式的说明:
This function's response will be pretty printed if the
JSONIFY_PRETTYPRINT_REGULARconfig parameter is set toTrueor the Flask app is running in debug mode. Compressed (not pretty) formatting currently means no indents and no spaces after separators.
如果
JSONIFY_PRETTYPRINT_REGULARconfig 参数设置为True或 Flask 应用程序在调试模式下运行,则此函数的响应将被打印出来。压缩(不漂亮)格式目前意味着分隔符后没有缩进和空格。
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。这应该不是问题,因为用于 JavaScript 消费的 JSON 不需要格式化(这只是要通过网络发送的额外数据),并且大多数工具格式都自己接收 JSON。
If you'd like to still use json.dumps(), you can send the proper mimetype by returning a Responsewith current_app.response_class().
如果您仍想使用json.dumps(),您可以通过返回一个Responsewith来发送正确的 mimetype 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")
For more on the difference:
有关差异的更多信息:
Prior to Flask 1.0, JSON handling was somewhat different. jsonifywould try to detect whether a request was AJAX and return pretty printed if it was not; this was removed because it was unreliable. jsonifyonly allowed dicts as the top-level object for security reasons; this is no longer applicable in modern browsers.
在 Flask 1.0 之前,JSON 处理有些不同。jsonify将尝试检测请求是否是 AJAX,如果不是,则返回打印得很漂亮;这被删除了,因为它不可靠。jsonify出于安全原因,只允许 dicts 作为顶级对象;这不再适用于现代浏览器。
回答by reubano
If for some reason you need to over-ride flask.jsonify(E.g., adding a custom json encoder) you can do so with the following method that implements the security fix @phpmycoder mentioned:
如果由于某种原因您需要覆盖flask.jsonify(例如,添加自定义 json 编码器),您可以使用以下方法来实现@phpmycoder 提到的安全修复:
from json import dumps
from flask import make_response
def jsonify(status=200, indent=4, sort_keys=True, **kwargs):
response = make_response(dumps(dict(**kwargs), indent=indent, sort_keys=sort_keys))
response.headers['Content-Type'] = 'application/json; charset=utf-8'
response.headers['mimetype'] = 'application/json'
response.status_code = status
return response
@app.route('/<major>/')
def major_res(major):
course = client.db.course_col.find({"major": (major.encode("utf8", "ignore").upper())})
return jsonify(**course)
@app.route('/test/')
def test():
return jsonify(indent=2, sort_keys=False, result="This is just a test")
Response:
回复:
{
"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"
}

