Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask load local json

Tags:

python

json

flask

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

like image 211
kOssi Avatar asked Jan 15 '14 09:01

kOssi


People also ask

How to display JSON data from local JSON file in HTML?

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.

Is there a JSON API for flask?

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.

How to print each attribute of the JSON object in flask?

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

How to run an application in flask with Python?

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.


2 Answers

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)
like image 163
kOssi Avatar answered Sep 26 '22 08:09

kOssi


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)
like image 27
cowgill Avatar answered Sep 25 '22 08:09

cowgill