2

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

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Bibek Paul
  • 142
  • 2
  • 9
  • 3
    The example in your post: `"45""56""78""75"` is definitely not a JSON format. – Christopher Jul 09 '20 at 03:53
  • 1
    That is not even close to being a proper JSON file, and also it's unclear how you want the code to work even looking beyond that. JSON is meant to be loaded all at once, not line-by-line. Any given line of a valid JSON file is probably not valid JSON. – Karl Knechtel Jul 09 '20 at 03:54
  • Hey and welcome, please read about hot to use JSON, https://www.w3schools.com/python/python_json.asp Also you can validate your JSON here https://jsonlint.com/?code= – InUser Jul 09 '20 at 04:01
  • "line-by-line" JSON exists: https://en.wikipedia.org/wiki/JSON_streaming#Line-delimited_JSON and e.g. for some kind of a log file is it a reasonable internal format. – VPfB Jul 09 '20 at 05:22

2 Answers2

4

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}
James Lin
  • 25,028
  • 36
  • 133
  • 233
1

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.