+1 vote
ago in Programming Languages by (89.5k points)

I am using the following code to read JSON data saved in a text file. However, this code returns the following error: 

raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper

The code is here:

with open('datafile.txt', 'r') as f:

    data = json.loads(f) 

What is wrong with this code?

1 Answer

+3 votes
ago by (17.1k points)
selected ago by
 
Best answer

That error is coming because you are trying to pass a file object (f) directly to json.loads(), which expects a string, not an open file handle. Use json.load() (not loads) when reading directly from a file object.

Here is the correct code:

import json

with open('datafile.txt', 'r') as f:

    data = json.load(f) 

json.load(f): use when reading from a file.

json.loads(some_string): use when parsing a string that contains JSON.


...