Mike Resoli Mike Resoli - 1 month ago 25
JSON Question

Reading a .json file using python - Flask

I'm trying to read a

.json
file from within my Flask application using:

def renderblog():
with open(url_for("static", filename="blogs.json")) as blog_file:
data = json.load(blog_file)


However I get the error:

FileNotFoundError: [Errno 2] No such file or directory: '/static/blogs.json'


Now I know for a fact that the directory exists within my project structure, but I have no idea why I'm getting this error. Any ideas? Is there a specific way to retrieve
.json
in Flask?

Answer

You generated a URL path, not a path to the local static folder. Use the app.static_folder attribute instead:

def renderblog():
    filename = os.path.join(app.static_folder, 'blogs.json')
    with open(filename) as blog_file:
        data = json.load(blog_file)
Comments