6

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

2 Answers 2

13

Use coalescing to pass it something valid.

json.loads('' or 'null')
Sign up to request clarification or add additional context in comments.

5 Comments

I tried to find an official python document explaining that concept. But couldn't find one. Can you give a hint?
This is a technical reference and not an explanation of the "coalescing" concept.
"The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned."
What you may want is: json.loads('' or '{}') - returns an empty dict instead of None. But this depends on your case of course.
0

To give another way that worked for me, I used the inline if which returns an empty string if there is no data to load: As seen below I wanted to load the request form data which is the session id

session_id = json.loads(request.form['session_id']) if request.form['session_id'] else ''

1 Comment

This will still fail if request.form['session_id'] is empty or None. As in else part you are again passing '' which leads to exception @LiLika

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.