Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Flask: Importing a .json file from a specific folder and returning on GET/POST request

Tags:

python

json

flask

am getting failures importing the JSON file from the folder, I have tried the convention:

from web_scraper import data

and also

from web_scraper.data import *

and both didn't work out. Also, how do I return the JSON file fetched? Is my method

return jsonify(bank_list)

the correct one? Here is the snapshot gotten from my PCPython-Flask

like image 971
Chai Chong Teh Avatar asked Jul 26 '26 07:07

Chai Chong Teh


1 Answers

Your import is wrong. First of all, you cannot import JSON in python. Only python files.

If it would be a python file, you'd have to use from ..web_scraper import data, as it's in the parent directory (assuming you didn't modify the pythonpath).

To load JSON, you can use the built-in json module.

import json
import os

with open(os.path.join(os.path.dirname(__file__), "web_scraper", "data.json")) as file:
    data = json.load(file)
# data is a dictionary that you can use in jsonify just fine

This would load the file's content and parse the JSON for later use, e.g. in jsonify. It's a normal dictionary

like image 149
Jens Reidel Avatar answered Jul 27 '26 22:07

Jens Reidel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!