7

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
StyleZ
  • 1,276
  • 3
  • 11
  • 27

1 Answers1

39

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
Nathan
  • 7,853
  • 4
  • 27
  • 50