调用函数时,出现标题中所述的错误:
def read_file(file_name):
"""Return all the followers of a user."""
f = open(file_name, 'r')
data = []
for line in f:
data.append(json.loads(line.strip()))
f.close()
return data
样本数据如下:
"from": {"name": "Ronaldo Naz\u00e1rio", "id": "618977411494412"},
"message": "The king of football. Happy birthday, Pel\u00e9!",
"type": "photo", "shares": {"count": 2585}, "created_time": "2018-10-23T11:43:49+0000",
"link": "https://www.facebook.com/ronaldo/photos/a.661211307271022/2095750393817099/?type=3",
"status_type": "added_photos",
"reactions": {"data": [], "summary": {"total_count": 51779, "viewer_reaction": "NONE"}},
"comments": {"data": [{"created_time": "2018-10-23T11:51:57+0000", ... }]}
答案 0 :(得分:3)
您正尝试将文件的每一行本身解析为JSON,这可能是错误的。您应该读取整个文件并立即转换为JSON,最好使用with
,以便Python可以处理文件的打开和关闭,即使发生异常也是如此。
由于json.load
接受一个文件对象并自行处理它的读取,因此整个内容可以精简为2行。
def read_file(file_name):
with open(file_name) as f:
return json.load(f)