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

查看:224
本文介绍了以整洁的方式显示从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的args作为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(),则可以通过返回 Response current_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")

有关差异的更多信息:

  • json.dumps vs flask.jsonify
  • flask.json module docs

在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天全站免登陆