Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 583
buhtz Avatar asked Feb 09 '18 16:02

buhtz


People also ask

How do you load a string as JSON in Python?

Use the json. you can turn it into JSON in Python using the json. loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary.

Can you JSON parse an empty string?

In Spark 3.0 and above, the JSON parser does not allow empty strings. An exception is thrown for all data types, except BinaryType and StringType .

What is JSON load ()?

json. load() takes a file object and returns the json object. A JSON object contains data in the form of key/value pair. The keys are strings and the values are the JSON types. Keys and values are separated by a colon.


1 Answers

Use coalescing to pass it something valid.

json.loads('' or 'null')
like image 58
Ignacio Vazquez-Abrams Avatar answered Sep 21 '22 04:09

Ignacio Vazquez-Abrams