首页 > 解决方案 > 奇怪的 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)

标签: pythonjsonpython-3.x

解决方案


通过读取文件

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)
>>> 

推荐阅读