如何从json文件加载列表?

时间:2018-03-11 15:04:07

标签: json python-3.x

我在text.txt中有这些数据:

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

当我尝试以这种方式加载时(第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']

我收到以下错误:

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)

我如何阅读数据?

1 个答案:

答案 0 :(得分:2)

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

由于f本质上是一个生成器,因此在f.read()条件中调用if会消耗它,并且在调用json.load(f)f为空:

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

您必须将文件的内容存储在变量中,然后使用json.loads

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