Skip to content
Advertisement

Opening .txt file in Python as Json file

I’ve searched Stackoverflow for a whole day, however I can’t seem to find the answer to my problem. I also tried several things, but it did not work; I don’t think the solution is very hard though, so maybe one of you can help me.

The .txt file is the following format:

{"text": "x x x x"}
{"text": "x x x x"}
{"text": "x x x x"}

It should be the following code:

with open("/Python map/Jsons scraped.txt") as jsonfile:    
          test2 = json.load(jsonfile)

However this leads to the following error (UnsupportedOperation: not readable)

I also tried adding ‘w’, ‘r’, ‘a+’, and other reading forms:

with open("/Python map/Jsons scraped.txt") as jsonfile:    
          test2 = json.load(jsonfile, 'w')

This leads to the following errors. With adding ‘w’ the error is still “UnsupportedOperation: not readable”. However, with using ‘r’ instead of ‘w’, the error becomes “JSONDecodeError: Expecting value”.

Does someone know what I can do?

Advertisement

Answer

The first thing is your JSON file format is wrong. it should be like this

[{"text": "x x x x"},
 {"text": "x x x x"},
 {"text": "x x x x"}]

Please notice I have added square bracket([]) at first and the last position also I added comma (,) after each JSON object

after that below, py code can help you reading JSON file

import json

f = open('json.txt', )
data = json.load(f)
print(data)
Advertisement