【问题标题】:Using Variables from Python Script when Importing JSON导入 JSON 时使用 Python 脚本中的变量
【发布时间】:2020-01-27 05:09:40
【问题描述】:

我有一个 Python 文件 main.py,其中包含以下代码,但它给了我错误消息:

day_of_event = '1990-12-25'
shopping_list = ['bread', 'cereal', 'water', 'soda', 'bananas']


with open(store_items.json) as file:
   json_file = json.loads(file)
   report = json_file["report"]

report = json.dumps(report)

以下是JSON文件store_items.json

{

"report" : "{'title' : 'grocery_report', 'date' : day_of_event, 'grocery_items' : shopping_list}"

}

如何读取 JSON 文件 store_items.json 并将 JSON 变量“report”导入 Python 文件,使 Python 脚本中的变量 report 等价于以下?

report = {'title' : 'grocery_report', 'date' : '1990-12-25', 'grocery_items' : ['bread', 'cereal', 'water', 'soda', 'bananas']}

【问题讨论】:

  • 您需要在打开的文件名“store_items.json”周围加上引号,并确保您在同一个文件夹中。您可以使用 os.path.abspath(os.curdir) 检查当前目录的位置。如果它与“store_items.json”不同,则需要提供文件的绝对路径。
  • 尝试使用 json.load() 代替 json.loads():with open('store_items.json') as file: data = json.load(file)['report']
  • 详情请见this post
  • JSON 文件的内容没有意义。 report 的值是一个看起来像 Python 文字的字符串。但它包含变量名——您是否希望使用eval() 来处理它?这似乎是非常糟糕的设计。
  • @Barmar 我认为这里更可能是示例文件内容被错误地复制,而不是实际文件错误。

标签: python json python-3.x


【解决方案1】:

要直接从文件中读取,你需要json.load而不是json.loadss 代表“字符串”,您正在从文件而不是字符串中读取。 (我同意这些名称可以而且应该更好。)此外,您的文件名需要被引用。在处理完这些之后,report = json_file["report"]已经为您提供了您想要的结果。 (.dumps 调用转换回字符串 - 再次,s 用于字符串,而不是写入打开的文件对象 - 因此不是您想要的。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    • 2019-03-03
    • 2015-02-24
    • 2020-01-15
    • 1970-01-01
    • 2020-09-25
    • 1970-01-01
    相关资源
    最近更新 更多