Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pretty Display JSON data from with Flask [duplicate]

Tags:

python

json

flask

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?

like image 438
Leustad Avatar asked May 20 '16 01:05

Leustad


1 Answers

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

like image 126
fulvio Avatar answered Oct 20 '22 14:10

fulvio