【发布时间】: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