Reputation: 11
The error occurs if I try to convert the json file into a variable and try to convert the file again to a separate variable is throws and error. I thought that json.load converts a json object to the python equivalent. So I am confused on why calling json.load(file) again would cause an error. Is the file still open or being used by the first call? I know I can get around it, I am just trying to understand json and the error. Using python 3.9.
#This code works:
def scores2(filedir):
for filename in os.listdir(filedir):
with open(os.path.join(filedir, filename), 'r') as read_file:
data = json.load(read_file)
#This code with the extra conversion to a new variable fails with error
def scores2(filedir):
for filename in os.listdir(filedir):
with open(os.path.join(filedir, filename), 'r') as read_file:
data = json.load(read_file)
dataextra= json.load(read_file)
The error is raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Upvotes: 1
Views: 784
Reputation: 2143
In your second set of code, the first json.load() reads all of the data in the file and leaves the read pointer at the end of the file. the subsequent .load() call gets a empty string which results in the error you get. You either need to:
Upvotes: 3