python - 奇怪的 JSONDecodeError
问题描述
这是我的代码,其中 AttrDict 是一个定语字典。我还将我的 json 解析为在线验证器,它说没关系。
available_langs = AttrDict({})
# Language import
for translation in os.listdir('translations'):
try:
if translation.split('.')[1] == 'json':
lang = translation.split('.')[0]
with open(f'translations/{translation}', 'r') as f:
print(f.read())
available_langs[lang] = load(f)
except IndexError:
pass
print(available_langs)
这是它试图解析的 eng.json
{
"start": {
"text": "Hello there!",
"markup": [{"start_picking": "Start picking"}, {"settings": "Settings"}]
},
"loading": {
"text": "Loading...",
"markup": null
}
}
我得到
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
解决方案
通过读取文件
print(f.read())
您正在将文件指针移动到文件的末尾,因此没有什么json.load
可读取的。
您可以重置文件指针
f.seek(0)
或者只是不要read
文件
或读取文件并使用反序列化结果字符串中的数据json.loads
with open(f'translations/{translation}', 'r') as f:
data = f.read()
print(data)
available_langs[lang] = json.loads(data)
示范
>>> d = {'a': 1}
>>> import json
>>> with open('foo.json', 'w') as f:
... json.dump(d, f)
...
>>> with open('foo.json') as f:
... f.read()
... json.load(f)
...
'{"a": 1}'
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File "/usr/local/lib/python3.7/json/__init__.py", line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "/usr/local/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/usr/local/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/lib/python3.7/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)
>>>
推荐阅读
- mysql - 如何使用 Perl Net::MySQL 更新和删除记录
- java - 如何通过 BLE 从 Android APP 向 BLE Reciever 发送数据?
- php - 如何使用 laravel 5.7 在邮件降价的表格单元格中显示图像?
- javascript - 在 Vue.js 单文件组件中使用 jQuery 插件
- dart - Flutter 中的音频播放器插件 - 无法加载资产
- c# - aspboilerplate 中的权限管理
- python-3.x - 如何在夹具中导入 python 并将它们用作 Pytest 中每个测试的全局变量?
- java - 如何使用 netcat 将 Cassandra 查询的整个结果发送到套接字
- android - how can i communicate to google home mini device with android app or vise-versa
- python - Python tkinter Menu