【发布时间】:2019-02-13 05:48:33
【问题描述】:
我有一个关于在 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 交互经验的人可以帮助我,那就太棒了。
【问题讨论】:
-
...发布 JSON?
-
我的超能力告诉我你的文件有一个UTF-8 BOM,你需要用
encoding='utf-8-sig'打开它。 -
@jwodder:不。
-
@jwodder 我很确定
json.load(甚至loads)处理UTF-8-sig;从那以后……无论哪个版本在 UTF-8 或 UTF-16 中添加二进制文件(和bytes),它也处理 UTF-8-sig,甚至(尽管没有记录)处理以 UTF-8 打开的 UTF-8-sig 文件文本。
标签: python json python-3.x io