Displaying JSON in the HTML using flask and local JSON file


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()

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

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


<!DOCTYPE html>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta charset="UTF-8" />
      var jsonfile ={{jsonfile}};
    <div class="container">


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:

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