I am struggling with how to load a local json in flask.
from flask import Flask, render_template, json, url_for
def taiwan():
json_data = open(url_for('static', filename="data/taiwan.json"))
data = json.load(json_data)
return render_template('taiwan.jade', data=data)
This raises an IOError: No such file or directory: '/static/css/taiwan.json'. But it still exists.
Any suggestions
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.
We now have a JSON API! It doesn’t do much at the moment, but it’s a start. Create a file named mock_data.py and place the contents of this gist into it. Since the end goal of teaching myself Flask is so that I can get Lists of Bests up and running again, we’ll use some fake data for possible book and album lists for the site.
You can print each attribute of the JSON object by accessing the dictionary by the name of the attribute, as shown bellow. Python version:3.6.0 Flask library: 0.12
This tutorial assumes the user to have the basic knowledge of Python programming language and Flask framework. Once you have Flask and Python installed in your system, create a file called app.py and paste the following code: Try running the app.py file and you should be able to view the application running at http://localhost:5000/getData.
I ended up with this:
import os
from flask import Flask, render_template, url_for, json
def showjson():
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
json_url = os.path.join(SITE_ROOT, "static/data", "taiwan.json")
data = json.load(open(json_url))
return render_template('showjson.jade', data=data)
Dynamically get your static directory and includes a data
sub-dir which contains the .json
file to load.
import os
from flask import Flask, render_template, json, current_app as app
# static/data/test_data.json
filename = os.path.join(app.static_folder, 'data', 'test_data.json')
with open(filename) as test_file:
data = json.load(test_file)
return render_template('index.html', data=data)
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