Everton Reis
Everton Reis

Reputation: 442

How to deal with json empty value

I'm a newbie into Python and i'm trying to open a json file that looks like this:

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

Let's say that this is the test.json file:

When trying to open it in python I'm using:

import json

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

and it raises the following error:

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)

It gives an error because of "empty_number": ,

How can I deal with this error if I can't modify my .json file?

Upvotes: 2

Views: 864

Answers (1)

jpp
jpp

Reputation: 164843

You can use the more flexible yaml to read in values not provided as 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'>

Note io.StringIO lets us read from a string as if it were a file.

Upvotes: 4

Related Questions