Skip to content Skip to sidebar Skip to footer

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

Solution 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>>>withopen('/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

>>>withopen('/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

>>>withopen('/tmp/a.json', 'r') as f:...for i in f:...print(json.loads(i))... 
{'a': 123}

Solution 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.

Post a Comment for "Python Json Attributeerror: 'str' Object Has No Attribute 'read'"