我想在Flask中创建Pretty JSON格式

时间:2019-01-11 16:45:41

标签: python json flask

我想在我的Flask网站(API网站)上输出漂亮的JSON,但是我的JSON文件不想正确格式化。

我尝试了多种方法:

return json.loads(json.dumps(json_text, indent=4))
return json.dumps(json_text, indent=4)
return jsonify(json_text)

json_it()函数:

def json_it(self):
    input_part = {"amount": self.amount, "currency": str(self.input_currency)}
    output_part = self.result
    return {"input": input_part, "output": output_part}

烧瓶API代码:

converter = CurrencyConvert(float(amount), input_currency, output_currency)
json_text = converter.json_it()
the_output = json.dumps(json_text, indent=10)
print(the_output)
return the_output, 200

CurrencyConvert将采用这三个参数,并根据其进行打印,如在输出该参数的输出中所见。 (那不应该是问题)

输出(API): 如果我打印出来:

{
          "input": {
                    "amount": 10.92,
                    "currency": "GBP"
          },
          "output": {
                    "AED": 46.023890640000005,
          }
}

如果我退货:

{ "input": { "amount": 10.92, "currency": "GBP" },"output": {"AED": 46.023890640000005,}}

我认为也提出了类似的问题,但是我找不到能够帮助我的解决方案。

1 个答案:

答案 0 :(得分:1)

您可以为烧瓶应用程序将JSONIFY_PRETTYPRINT_REGULAR属性设置为 true ,以便以适当的缩进级别打印JSON响应。

app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True