Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to make Pretty JSON formatting in Flask [duplicate]

Tags:

python

json

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.

like image 712
StyleZ Avatar asked Jan 11 '19 16:01

StyleZ


People also ask

How do I make JSON data look pretty?

If you're starting from a valid JSON string that you want to pretty printed, you need to convert it to an object first: var jsonString = '{"some":"json"}'; var jsonPretty = JSON. stringify(JSON. parse(jsonString),null,2);

How do I pretty-print a JSON object?

We can pretty-print a JSON using the toString(int indentFactor) method of org. json. JSONObject class, where indentFactor is the number of spaces to add to each level of indentation.

Does Flask automatically Jsonify?

No, returning a dict in Flask will not apply jsonify automatically. In fact, Flask route cannot return dictionary.


1 Answers

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
like image 147
Nathan Avatar answered Oct 11 '22 20:10

Nathan