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.
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.
return json_encode([], JSON_FORCE_OBJECT); it returns "{}" instead of {} only without the double quotes.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With