Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
导入JSON时使用Python脚本中的变量_Python_Json_Python 3.x - Fatal编程技术网

导入JSON时使用Python脚本中的变量

导入JSON时使用Python脚本中的变量,python,json,python-3.x,Python,Json,Python 3.x,我有一个包含以下代码的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.du

我有一个包含以下代码的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\u 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']}

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

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