【问题标题】:Python - Flask: Importing a .json file from a specific folder and returning on GET/POST requestPython - Flask:从特定文件夹导入 .json 文件并返回 GET/POST 请求
【发布时间】:2019-03-16 10:52:21
【问题描述】:

从文件夹中导入 JSON 文件失败,我尝试了约定:

from web_scraper import data

还有

from web_scraper.data import *

两者都没有成功。 另外,如何返回获取的 JSON 文件?是我的方法

return jsonify(bank_list)

正确的? 这是从我的电脑上得到的快照

【问题讨论】:

  • 我试过j = os.path.join(os.path.dirname( os.path.abspath(__file__)), 'data.json') data = json.load(j) return jsonify(data) 导致“AttributeError: 'str' object has no attribute 'read'”

标签: python json flask


【解决方案1】:

您的导入错误。 首先,你不能在 python 中导入 JSON。只有 python 文件。

如果它是一个 python 文件,你必须使用from ..web_scraper import data,因为它在父目录中(假设你没有修改 pythonpath)。

要加载 JSON,可以使用内置的 json 模块。

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

这将加载文件的内容并解析 JSON 以供以后使用,例如在jsonify。这是一本普通的字典

【讨论】:

  • 感谢 Jens,我已经接近它了。但是,它以语法错误with open(os.path.join(os.path.dirname(__file__), "web_scraper", "data.json") as file: 进行响应,箭头指向“as”字。任何线索为什么?
  • 我的错,添加另一个关闭 ) ;) - 我更新了 sn-p
  • 感谢提醒,没注意到 XD 非常感谢。
猜你喜欢
  • 2017-05-22
  • 1970-01-01
  • 2018-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-17
  • 2023-02-26
相关资源
最近更新 更多