Max315
Max315

Reputation: 11

Python Error when using json.load on the same file again

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

Answers (1)

LhasaDad
LhasaDad

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:

  1. have your two json blobs in different files and read them separately or
  2. you need to use loads() to load the json object from a string and manage the data in the file with read operations that read part of the file that contains the individual sections of json. you would read the data in as a string then pass it to loads()

Upvotes: 3

Related Questions