Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing json to dump a json object even when list is empty

Tags:

python

json

I have a list, which may be empty or non-empty.

I want to create a new file which contains that list in a format that is human-readable and easy for my next script to parse. In the case where the list is non-empty, this works fine and my next script reads in the json file. But when the list is empty, I get "ValueError: No JSON object could be decoded." This makes sense, because when I open the file, there is indeed no content and thus no JSON object.

I'm OK with the fact that some lists are empty. So, either I want to write an empty JSON object or I want my reader script to be OK with not finding a JSON object.

Here's the relevant code:

Writer Script

favColor = []   OR   favColor = ['blue']   OR favColor = ['blue', 'green']
fileName = 'favoriteColor.json'
outFile = open(fileName, 'w')
json.dump(outFile, favColor)
outFile.close()

Reader Script

fileName = 'favoriteColor.json'
inFile = open(fileName, 'r')
colors = json.load(inFile)
inFile.close()

Any help or suggestions much appreciated. If I need to provide more rationale for why I'm doing this, I can provide that as well, just thought I'd start off with minimum necessary to understand the problem.

like image 826
rcorty Avatar asked Aug 02 '12 15:08

rcorty


People also ask

What is the difference between JSON dump and JSON dumps?

dump() method used to write Python serialized object as JSON formatted data into a file. json. dumps() method is used to encodes any Python object into JSON formatted String.

How do I return an empty JSON response?

return json_encode([], JSON_FORCE_OBJECT); it returns "{}" instead of {} only without the double quotes.

What is JSON dumps () method?

The dump() method is used when the Python objects have to be stored in a file. The dumps() is used when the objects are required to be in string format and is used for parsing, printing, etc, . The dump() needs the json file name in which the output has to be stored as an argument.


1 Answers

Modify your reader script to this:

with open('favoriteColor.json') as inFile:
    try: 
         colors = json.load(inFile)
    except ValueError: 
         colors = []

This attempts to load the file as a json. If it fails due to a value error, we know that this is because the json is empty. Therefore we can just assign colors to an empty list. It is also preferable to use the "with" construct to load files since it closes them automatically.

like image 184
Lanaru Avatar answered Oct 01 '22 13:10

Lanaru