如何处理json空值

时间:2018-05-22 16:30:19

标签: python json dictionary

我是Python的新手,我正在尝试打开一个看起来像这样的json文件:

{
  "empty_char":"",
  "empty_number": ,
  "char":"i'm a char",
  "number":0
}

假设这是test.json文件:

尝试在python中打开它时我正在使用:

import json

with open('test.json') as f:
    data = json.load(f)

并引发以下错误:

Traceback (most recent call last):
  File "<input>", line 2, in <module>
  File "C:\ProgramData\Anaconda3\Lib\json\__init__.py", line 299, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "C:\ProgramData\Anaconda3\Lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\ProgramData\Anaconda3\Lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\ProgramData\Anaconda3\Lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 3 column 19 (char 39)

由于"empty_number": ,

,它会出错

如果我无法修改.json文件,我该如何处理此错误?

1 个答案:

答案 0 :(得分:4)

您可以使用更灵活的yaml来读取未提供为None的值。

import yaml
from io import StringIO

mystr = StringIO("""{
  "empty_char":"",
  "empty_number": ,
  "char":"i'm a char",
  "number":0
}""")

# replace mystr with open('test.json', 'r')
with mystr as stream:
    res = yaml.load(stream)

print(res, type(res))

{'empty_char': '', 'empty_number': None, 'char': "i'm a char", 'number': 0}
<class 'dict'>

注意io.StringIO让我们从字符串中读取,就像它是一个文件一样。