在单个文件中保存多个 Json 对象

Saving multiple Json object in single file

我正在尝试为组织解析 github api link first link 我从这个 link 收集了所有 commit_url,然后我需要保存每个提交 link 的数据以进行进一步清理。

例如我有两个提交 link 作为 commit_link1 and commit_link2

因为两个 links 中的数据又是 JSON 对象,我尝试使用追加模式将数据保存在 JSON 文件中,但是当我打开文件以获取数据时,出现了键盘错误:额外数据

知道我应该如何将数据保存在单个文件中作为 CSV 选项看起来不合理。

JSON 文件中的顶级项目必须是单个值,例如单个对象(Python 中的 dict)或单个列表。因此,您不能简单地将两个 JSON 对象附加到一个文件中。

您可以将所有这些对象收集到一个列表中,然后存储该列表,或者您可以使用 JSON Lines file format, which consists of multiple JSON values (e.g. objects), separated by newlines. Note however, that "standard" JSON tools won't know how to deal with JSON Lines. For Python, you can use the jsonlines 库。

对于正在查看这个老问题的任何人: JSON-lines 是个不错的选择。它是 json,但每一行都是一个 json(即 json 由 '\n' 分隔)

节省:

(*.jsonl 是 json 行的典型文件扩展名)

import json

file_name = "data.jsonl"  # your desired file name  
list_objs = []  # the list of objects you want to save as json

# convert object to strings
text = "\n".join([json.dumps(json_) for json_ in list_objs])

# save
with open(file_name, "w", encoding='utf-8') as f:
    f.write(text)

正在加载:

import json

file_path = "#####.jsonl"  # your file path

data = []
with open(file_path, "r", encoding='utf-8') as f:
    for line in f:
        data.append(json.loads(line))