Eduard
Eduard

Reputation: 9165

How to load a list from a json file?

I have this data inside my text.txt:

[{"title": "T", "genre": "G", "director": "D", "year": "R"}]

When I try to load it this way (line 6):

class Movie:
    def __init__(self, **new_movie):
        movies = []
        with open ('movies.txt', 'r') as f:
            if f.read() != '':
                movies = json.load(f)
        if not verify_uniqueness(new_movie, movies):
            print('Movie has already been added.')
        else:
            self.title = new_movie['title']
            self.genre = new_movie['genre']
            self.director = new_movie['director']
            self.year = new_movie['year']

I get the following error:

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 299, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

How can I read the data?

Upvotes: 0

Views: 1380

Answers (1)

DeepSpace
DeepSpace

Reputation: 81604

with open ('movies.txt', 'r') as f:
    if f.read() != '':
        movies = json.load(f)

Since f is essentially a generator, calling f.read() in the if condition consumes it, and by the time json.load(f) is called f is empty:

with open ('movies.txt') as f:
        print(f.read())
        # file content
        print(f.read())
        # ''

You have to store the file's content in a variable and then use json.loads:

with open('movies.txt') as f:
    content = f.read()
    if content:
        movies = json.loads(content)

Upvotes: 2

Related Questions