【发布时间】:2019-07-12 02:24:29
【问题描述】:
我刚开始学习 JSON,我想从我的电脑上读取一个 JSON 文件。
我用json.loads() 尝试过这个,我得到这个错误:json.decoder.JSONDecodeError: Expecting ',' delimiter: line 9 column 20 (char 135)。
所以我尝试使用open()从我的 PC 加载 JSON 文件中的数据,但我发现它没有返回字符串类型的输出,并且它给出了错误:TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper。
然后我尝试使用read() 并给出错误:json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
我试过这些:
1)
with open('FILE.json') as f:
data = json.loads(f.read())
2)
with open('FILE.json') as f:
data = json.loads(f)
3)
with open('FILE.json', 'r', encoding='utf-8') as f:
data = json.loads(f.read())
【问题讨论】:
-
error
Expecting value: line 1 column 1 (char 0)表示您从空文件中读取。它无法解码空字符串。最好检查您在此文件中的内容。或者您可能从不同的文件中读取数据。 -
@furas 那只是表示文件格式不正确。
-
@furas, @aero blue 在这种情况下,文件已被读取。在每次读取之间,需要重新打开文件或需要使用
f.seek(0)回到开头。 -
尽管
line 9 column 20 (char 135),您的问题确实是第一个错误。这表明您需要修复 JSON 文件中的格式错误,如果格式正确,您的第一个示例实际上将正确读取 JSON。
标签: python json python-3.x