附加到 python 中的空 JSON 文件中

Appending into an empty JSON file in python

我已经有一个 JSON 文件,我正在使用 Python 2.7 解析它,我想将解析出的数据转储到另一个空的 JSON 文件中。我正在使用 for 循环从旧的 JSON 文件中解析出数据,同时在该循环中我想附加到新的 JSON 文件。我原来的 JSON 文件是 JSON 数组的形式。注意:新的 JSON 文件将与旧的 JSON 文件具有相同的键,即我只是根据 if 条件解析数据,然后插入整个索引(满足条件)从旧的 JSON 到新的 JSON。 旧 JSON = "output_log.json" 新 JSON = "cumulative_output.json"

新的 JSON 文件将是一个索引列表,例如:

[{"name":".....", "commit":".....", "author":"...", "title":"...", "body":"..."},
{"name":".....", "commit":".....", "author":"...", "title":"...", "body":"..."},
.........
]
    with open("output_log.json", 'r') as f:
        json_ob = json.load(f)
      
        for index in range(len(json_ob)):
            if (bool(re.search(r"\s", json_ob[index]['name']))) is True and ('444' in json_ob[index]['title']) and ('https://robotics.com/projects/' in json_ob[index]['body']):
                with open('cumulative_output.json', 'a') as f:
                    entry = {'name': json_ob[index]['name'], 'commit': json_ob[index]['commit'], 'author': json_ob[index]['author'], 'title': json_ob[index]['title'], 'body': json_ob[index]['body']}
                    f.write(entry)
                    f.write(",")

您正在读写单个 JSON 列表对象,因此没有太多机会以迭代方式执行操作。您当前的代码失败是因为您无法在没有某种序列化的情况下编写 python 字典 (f.write(entry))。读完 JSON 列表,你可以过滤它,然后再写。您不需要为您阅读的列表编制索引的额外复杂性,只需对其进行迭代即可。并且由于您要写入整个记录,因此无需创建新字典。

with open("output_log.json") as f:
    json_ob = json.load(f)

entries = []
for entry in json_ob:
    if (re.search(r"\s", entry["name"]) and ("444" in entry["title"])
            and (r"https://robotics.com/projects/" in entry["body"])):
        entries.append(entry)

with open("cumulative_output.json", "w") as f:
    json.dump(entries)