【问题标题】:Create JSONL with Python使用 Python 创建 JSONL
【发布时间】:2019-11-26 00:34:57
【问题描述】:

我不知道如何使用 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"}

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

【问题讨论】:

  • 您希望测试中的每个项目作为输出文件中的新行吗?
  • @Rakesh 是的,这正是我想要的。

标签: python-3.x jsonlines


【解决方案1】:

使用.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)

【讨论】:

  • 你说得对,是想多了——这似乎是有效的 JSONL。谢谢
猜你喜欢
  • 1970-01-01
  • 2021-05-25
  • 2021-07-29
  • 2021-08-24
  • 2016-12-19
  • 2021-08-21
  • 2021-11-22
  • 1970-01-01
  • 2021-04-01
相关资源
最近更新 更多