pythonjsonflask

I want to make Pretty JSON formatting in Flask


I would like to output a nice looking JSON on my flask website (API website) , but my JSON file does not want to format properly.

I have tried multiple things :

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

json_it() function:

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}

Flask API code:

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 is taking those 3 parameters and makes dictionaty from it as you can see in the output that prints it. ( that one should not be the problem )

OUTPUT ( API ) : If I print it:

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

If I return it:

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

I think similar questions were asked, but I could not find the solution that could help me.


Solution

  • Flask >= v2.3.x

    You can set the attribute compact explicitly to False when running in production mode or leave as default (None) in development mode to pretty print responses:

    app.json.compact = False
    

    Flask < v2.3.x

    You can set the JSONIFY_PRETTYPRINT_REGULAR property to true for your flask application so your JSON responses print with the proper indentation levels.

    i.e.

    app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True