Flask load local json

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)

You should use the path of Your static dir, to obtain the file, url_for gets the URI abs path, not fs path. Try this

json_data = open(os.path.join(your_static_dir, "data", "taiwan.json"), "r")

Tags:

Python

Json

Flask