本文介绍了Flask的jsonify()中的缩小的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Flask提供便捷的jsonify()函数,该函数从Python变量返回JSON对象:

Flask offers the convenient jsonify() function, which returns a JSON object from Python variables:

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)

哪个返回:

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

(PS-注意从int到string的转换以符合JSON).

(PS - note the conversion from int to string to comply with 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}

如何从Flask的jsonify()中获取缩小版本的JSON?

How can I get the JSON in minified version from Flask's jsonify()?

推荐答案

只需设置配置键 JSONIFY_PRETTYPRINT_REGULAR False-Flask漂亮打印JSON,除非AJAX请求(默认情况下)请求了.

Simply set the configuration key JSONIFY_PRETTYPRINT_REGULAR to False - Flask pretty-prints JSON unless it is requested by an AJAX request (by default).

这篇关于Flask的jsonify()中的缩小的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 10:26