Python-可以读取JSON数据,但不能设置为变量

问题描述 投票:-1回答:2

我正在尝试能够从JSON文件加载类实例。由于某些原因,可以从文件读取JSON数据(请参见print行),但不能将其设置为变量。

JSON文件内容:

{"key": 1}

with open(json_path) as json_file:
    print(json.load(json_file)) # prints {'key': 1}
    class_dict = json.load(json_file)

我收到此错误:

raise JSONDecodeError("Expecting value", s, err.value) from None

JSONDecodeError: Expecting value

我尝试使用字符串值json.loadjson.loads。我尝试向open函数添加其他参数。没有一个有效。我在这里验证了JSON:https://jsonlint.com/

python json
2个回答
1
投票

我同意@Scott Hunter,您已经使用第一个json.load语句读取了文件。如果您需要直接分配内容,则可以倒带该文件。

with open(json_path) as json_file:
    print(json.load(json_file))
    json_file.seek(0)
    class_dict =  json.load(json_file)
    print class_dict

1
投票

您两次加载文件的依据

with open(json_path) as json_file:
    print(json.load(json_file)) # prints {'key': 1}
    class_dict = json.load(json_file)

第一个json.load(json_file)将完全加载打开的文件,因此第二次不再需要读取。

如果要打印并分配它,请先分配它,然后再打印:

with open(json_path) as json_file:
    class_dict = json.load(json_file)
    print(class_dict) # prints {'key': 1}
© www.soinside.com 2019 - 2024. All rights reserved.