Amr Mahmoud
Amr Mahmoud

Reputation: 21

How to read json file in python?

I just started learning JSON, and I want to read a JSON file from my PC.

I tried this with json.loads(), I am getting this error: json.decoder.JSONDecodeError: Expecting ',' delimiter: line 9 column 20 (char 135).

So I tried to load the data from JSON file from my PC , with open(), but I found out that it doesn't return a String type output, and it gives the error: TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper.

Then I tried using read() and also gives the error: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I've tried these:

1)

with open('FILE.json') as f:
        data = json.loads(f.read())

2)

with open('FILE.json') as f:
        data = json.loads(f)

3)

with open('FILE.json', 'r', encoding='utf-8') as f:
          data = json.loads(f.read())

Upvotes: 1

Views: 3569

Answers (2)

agupta
agupta

Reputation: 175

Based on reading over the documentation

Try this:

with open(absolute_json_file_path, encoding='utf-8-sig') as f:
    json_data = json.load(f)
    print(json_data)

Upvotes: 1

Aero Blue
Aero Blue

Reputation: 526

You want to use json.load() instead of json.loads()

Example:

 with open(file.json) as f:

      x = json.load(f)

Upvotes: 1

Related Questions