Bibek Paul
Bibek Paul

Reputation: 162

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:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\json\__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

Upvotes: 2

Views: 11035

Answers (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.

Upvotes: 1

James Lin
James Lin

Reputation: 26568

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}

Upvotes: 4

Related Questions