Python JSON AttributeError: 'str' object has no attribute 'read'

I am a beginner in Python. Python 3.7.6

import json
fil='numbers.json'
num=[]
with open(fil,'r') as file :
    for obj in file :
        num.append(json.load(obj))
print(num)

This is the JSON file :

"45""56""78""75"

This is the error I am getting while running the code

Traceback (most recent call last):
  File "C:/Users/Dell/PycharmProjects/untitled/tetu.py", line 6, in <module>
    num.append(json.load(obj))
  File "C:UsersDellAppDataLocalProgramsPythonPython38libjson__init__.py", line 293, in load
    return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'

Any idea how I can fix this?

Thanks in advance

Answer #1:

Firstly your file content is not json.

Given a valid json file content /tmp/a.json:

{"a": 123}

json.load() accepts file object like:

>>> import json
>>> with open('/tmp/a.json', 'r') as f:
...     data = json.load(f)
...     print(data)
... 
{'a': 123}

Your error comes from iterating the file object, which reads each line into string

>>> with open('/tmp/a.json', 'r') as f:
...     for i in f:
...             print(i.__class__)
... 
<class 'str'>

In this case, you will need to use json.loads() which accepts a json string

>>> with open('/tmp/a.json', 'r') as f:
...     for i in f:
...             print(json.loads(i))
... 
{'a': 123}
Answered By: James Lin

Answer #2:

Putting aside the use of json extension for a non-json file, the issue with your code is that obj is a string in your code, not a file, so you should use json.loads instead of json.load. On the other hand, if you know that each line is a number, you may convert the literal integer with int.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .



# More Articles