我想在 Flask 中制作漂亮的 JSON 格式

Sty*_*leZ 5 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)
Run Code Online (Sandbox Code Playgroud)

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}
Run Code Online (Sandbox Code Playgroud)

烧瓶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
Run Code Online (Sandbox Code Playgroud)

CurrencyConvert 正在使用这 3 个参数,并根据它制作字典,正如您在打印它的输出中看到的那样。(那个应该不是问题)

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

{
          "input": {
                    "amount": 10.92,
                    "currency": "GBP"
          },
          "output": {
                    "AED": 46.023890640000005,
          }
}
Run Code Online (Sandbox Code Playgroud)

如果我退货:

{ "input": { "amount": 10.92, "currency": "GBP" },"output": {"AED": 46.023890640000005,}}
Run Code Online (Sandbox Code Playgroud)

我认为有人问过类似的问题,但我找不到可以帮助我的解决方案。

Nat*_*han 23

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

IE

app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
Run Code Online (Sandbox Code Playgroud)

  • 如果我只想让一个处理程序变得漂亮而不是全部处理程序怎么办? (2认同)