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.
Modify your reader script to this:
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.