Displaying JSON in the HTML using flask and local JSON file

Issue

I work with the Python flask, HTML, and local JSON file to display the JSON data from a local JSON file in the HTML. Once the flask reads a local JSON file, it is sent to index.html with jsonify. After then, using that data I want to display the information.

I can the JSON data in the flask side, but have struggled with displaying it in the HTML. Could you let me know what I missed?

flask code


import os
from flask import Flask, render_template, abort, url_for, json, jsonify
import json
import html

app = Flask(__name__)

# read file
with open('./data/file.json', 'r') as myfile:
    data = myfile.read()

@app.route("/")
def index():
    return render_template('index.html', title="page", jsonfile=jsonify(data))

app.run(host='localhost', debug=True)

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta charset="UTF-8" />
    <title>House</title>
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
      integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
      crossorigin="anonymous"
    />
    <script>
      var jsonfile ={{jsonfile}};
    </script>
  </head>
  <body>
    <div class="container">
    {{jsonfile}}
  </div>
  </body>
</html>

Solution

Your issue is the use of the jsonify method. If you read the documentation of jsonify it returns a Response object and not a string. So you will get something like this for jsonify(data)

<Response 2347 bytes [200 OK]>

You could remove jsonify and use json.dumps instead, as follows:

@app.route("/")
def index():
    return render_template('index.html', title="page", jsonfile=json.dumps(data))

This works for me.

Answered By – Rahul P

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published