Load an Empty String as a Json in Python3

Load an Empty String as a Json in Python3

I can not use an empty string in json.loads().

Python 3.6.4 (default, Jan  5 2018, 02:13:53) 
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> json.loads('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Is there a way to prevent the JSDONDecodeError and just return a default value (e.g. empty dict, list or None)? if json.loads() handle an empty string?

The background of my question is I read file contents and parse them with json.loads. But sometimes the files are empty (size=0). This is ok and not an error. But I don't want to check the file size or content size before using json.loads().

0

1 Answer

Use coalescing to pass it something valid.

json.loads('' or 'null')
5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.