简体   繁体   English

在烧瓶的 jsonify() 中缩小 JSON

[英]Minified JSON in flask's jsonify()

Flask offers the convenient jsonify() function, which returns a JSON object from Python variables: Flask 提供了方便的jsonify()函数,它从 Python 变量返回一个 JSON 对象:

from flask import Flask, jsonify
app = Flask(__name__)

@app.route("/")
def json_hello():
    return jsonify({x:x*x for x in range(5)}), 200

if __name__ == "__main__":
    app.run(debug=True)

Which returns:返回:

{
  "0": 0, 
  "1": 1, 
  "2": 4, 
  "3": 9, 
  "4": 16
}

(PS - note the conversion from int to string to comply with JSON). (PS - 注意从 int 到 string 的转换以符合 JSON)。

This indented format is wasteful for long outputs, and I prefer the minified version:这种缩进格式对于长输出来说是浪费的,我更喜欢缩小版本:

{"1": 1, "0": 0, "3": 9, "2": 4, "4": 16}

How can I get the JSON in minified version from Flask's jsonify() ?如何从 Flask 的jsonify()获取缩小版本的 JSON?

In addition to the other answer of JSONIFY_PRETTYPRINT_REGULAR , you can also get rid of the spaces between list elements by extending flask's jsonencoder, like so:除了JSONIFY_PRETTYPRINT_REGULAR的其他答案JSONIFY_PRETTYPRINT_REGULAR ,您还可以通过扩展flask的jsonencoder来消除列表元素之间的空格,如下所示:

from flask import Flask
from flask.json import JSONEncoder

class MiniJSONEncoder(JSONEncoder):
    """Minify JSON output."""
    item_separator = ','
    key_separator = ':'

app = Flask(__name__)
app.json_encoder = MiniJSONEncoder
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False

The default values for item_separator and key_separator have a trailing space each, so by overriding them like this, you remove those spaces from the output. item_separatorkey_separator的默认值每个都有一个尾随空格,因此通过像这样覆盖它们,您可以从输出中删除这些空格。

(strictly speaking I suppose you could just set those values on the default JSONEncoder but I needed this approach since I had to overload JSONEncoder.default() for other reasons anyway) (严格来说,我想你可以在默认的JSONEncoder上设置这些值,但我需要这种方法,因为无论如何我不得不因其他原因重载JSONEncoder.default()

只需将配置键JSONIFY_PRETTYPRINT_REGULAR设置为False - Flask 会漂亮地打印 JSON,除非它是由 AJAX 请求(默认情况下)请求的。

Flask 1.1 will add indents and spaces to the jsonify() output if current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] is True ( False by default) or the app is in debug mode.如果current_app.config["JSONIFY_PRETTYPRINT_REGULAR"]True (默认为False )或应用程序处于调试模式,Flask 1.1 将向 jsonify() 输出添加缩进和空格。

indent = None
separators = (",", ":")

if current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] or current_app.debug:
    indent = 2
    separators = (", ", ": ")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM