I've got a response object as a result of a GET
request and I've converted this to JSON
with jsonify()
. When I pass this to a template, all I get is a JSON object like: <Response 1366 bytes [200 OK]>
this.
#request.py
...
response = requests.get('http://www.example.com')
response_json = jsonify(all=response.text)
return render_template(
'results.html',
form=ReqForm(request.form),
response=response_json,
date=datetime.datetime.now()
)
and the template..
#results.html
...
<div class="results">
{{ response }} # --> gives <Response 1366 bytes [200 OK]>
</div>
...
How can I pretty display this JSON in a template?
Use json.dumps
response = json.dumps(response.text, sort_keys = False, indent = 2)
or to make it prettier
response = json.dumps(response.text, sort_keys = True, indent = 4, separators = (',', ': '))
Template
#results.html
...
<div class="results">
<pre>{{ response }}</pre>
</div>
...
The jsonify()
function in flask returns flask.Response()
object that already has the appropriate content-type header 'application/json'
for use with json responses, whereas the json.dumps()
will just return an encoded string, which would require manually adding the mime type header.
Source: https://stackoverflow.com/a/13172658/264802
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With