首页 > 解决方案 > 如何通过简单的文件读取加载 jsonlines 文件

问题描述

考虑有下面的代码和一个jsonl文件,
有一个特定的原因我不使用jsonlines.open()api 读取文件,所以请将此作为事实。

jsonlines 包的参考: https ://jsonlines.readthedocs.io/en/latest/#jsonlines.Reader

import jsonlines

with open('example.jsonl', 'r') as jsonl_f:
    content = jsonl_f.read()

with jsonlines.Reader(content) as reader:
    lst = [obj for obj in reader]

example.jsonl内容:

{"hello": "world"}
{"covid": "19"}

我上lst=线的错误:

 lst = [obj for obj in reader]
  File "../lib/python3.7/site-packages/jsonlines/jsonlines.py", line 204, in iter
    skip_empty=skip_empty)
  File "../lib/python3.7/site-packages/jsonlines/jsonlines.py", line 164, in read
    six.raise_from(exc, orig_exc)
  File "<string>", line 3, in raise_from
jsonlines.jsonlines.InvalidLineError: line contains invalid json: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) (line 1)

标签: pythonjsonpython-3.xjsonlines

解决方案


import jsonlines

with jsonlines.open('example.jsonl', 'r') as jsonl_f:
     lst = [obj for obj in jsonl_f]

jsonl_f是阅读器,可以直接使用。它包含 json 文件中的行。


推荐阅读