Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pretty Print a json file when returning in a flask function

Tags:

python

json

flask

I am looking to figure out how I can pretty print a json file when I return it in a flask function. I have managed to pretty print it using json.dump but not with the flask function. this is what I have":

from flask import Flask, jsonify
import flask
import json

app = Flask(__name__)

with open('VO/IFATC EG/qotd.json') as qotd_file:
    data = json.load(qotd_file)

    rr = data['questions']
    car = json.dumps(data, indent=4)
    print(car)

@app.route('/')
def words():
    return json.dumps(data, indent=4)

app.run()

it prints car but I just get

enter image description here

Thanks

like image 552
SPEEDBIRD101 Avatar asked Nov 19 '25 21:11

SPEEDBIRD101


1 Answers

There is a config option JSONIFY_PRETTYPRINT_REGULAR which allows you to do this.

from flask import Flask, jsonify
import flask
import json

app = Flask(__name__)
app.config["JSONIFY_PRETTYPRINT_REGULAR"] = True

with open('VO/IFATC EG/qotd.json') as qotd_file:
    data = json.load(qotd_file)

    rr = data['questions']
    car = json.dumps(data, indent=4)
    print(car)

@app.route('/')
def words():
    return jsonify(data)

app.run()

Note that the return uses jsonify instead of json.dumps.

like image 59
Henry Avatar answered Nov 21 '25 11:11

Henry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!