Get AttributeError: 'str' object has no attribute 'read' when trying to print data from a JSON file

Viewed 155

I am trying to read the data from this JSON file and then eventually print out specific data from the file. The issue is during this initial step of just trying to print all of the data, I get the error "AttributeError: 'str' object has no attribute 'read'".

def jsonLang(fileName):
    with open(fileName) as jsonFile:
        jsonData = json.load(fileName)
        print(jsonData)


jsonLang("/users/sully/repos/30DaysOfPython/textCount/countries_data.json")
1 Answers

Change:

jsonData = json.load(fileName)

To:

jsonData = json.load(jsonFile)

Explanation: because fileName is a string, you cannot read it as a file using load. The proper variable to use is the open file handle, jsonFile.

Related