我对在 Python 中使用 json 库时遇到的问题有疑问。
我想通过以下代码使用 json.load(file) 命令读取 json 文件:
import json
filename= '../Data/exampleFile.json'
histFile= open(filename, 'w+')
print(json.load(histFile))
根据我发现的一些网站,我尝试读取的 JSON 文件是有效的:a screenshot of that validation, because I'm new and still lack the reputation...
我收到的错误消息如下:
File ".\testLoad.py", line 5, in <module>
print(json.load(histFile))
File "C:\Users\...\Python\Python37\lib\json\__init__.py", line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\Users\...\Python\Python37\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\...\Python\Python37\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\...\Python\Python37\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
好吧,所以我相信问题不是文件,而是 json.load(file) 在其他情况下对我有用。
遗憾的是,我无法自己解决这个错误消息,所以如果有更多处理 Python-JSON 交互经验的人可以帮助我,那就太棒了。
最佳答案
您打开文件进行写入:
histFile= open(filename, 'w+')
# ^^^^
w
模式首先截断文件,所以文件是空的(这里没关系文件也可以读取, +
看到了这一点,但文件仍然被截断了)。查看open()
function documentation :
'w'
: open for writing, truncating the file first)
其中没有要解析的 JSON 数据。这就是异常告诉您解析在文件的最开头失败的原因:
Expecting value: line 1 column 1 (char 0)
第一行第一列没有数据
如果您想打开一个文件同时进行读写,而不首先截断它,请使用'r+'
作为文件模式。
关于有效 JSON 的 Python json.load(file) 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52229903/