使用 Python 创建 JSONL

Create JSONL with Python

我不知道如何使用 Python3 创建 JSONL

test = [{'a': 'b'}, {'a': 'b'}, {'a': 'b'}]

with open("data.json", 'w') as f:
    for item in test:
        json.dump(item, f)

with open("data.json") as f:
    for line in f:
        // only 1 line here! 
        print(line)

// prints
{"a": "b"}{"a": "b"}{"a": "b"}

我试过使用缩进选项进行转储,但它似乎没有什么不同,分隔符选项似乎不是一个很好的用例。不确定我在这里缺少什么?

使用 .write 换行符 \n

例如:

import json
test = [{'a': 'b'}, {'a': 'b'}, {'a': 'b'}]

with open("data.json", 'w') as f:
    for item in test:
        f.write(json.dumps(item) + "\n")

with open("data.json") as f:
    for line in f:
        print(line)