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
Thanks
CodePudding user response:
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
.
CodePudding user response:
In your html, put it beween these tags:
<pre><code>your_return_json here</code></pre>
Suggestion: use jinja2 html template en return render_template
from flask import Flask, jsonify, render_template
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 render_template('your_template.html from a templates subfolder', data=json.dumps(data, indent=4))
app.run()
and a template.html file in a folder templates/ with contents:
<pre><code>{{ data }}</code></pre>