使用 Python 创建 JSONL

rix*_*rix 15 python-3.x jsonlines

我不知道如何使用 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"}
Run Code Online (Sandbox Code Playgroud)

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

Rak*_*esh 25

.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)
Run Code Online (Sandbox Code Playgroud)