【问题标题】:Appending into an empty JSON file in python在python中附加到一个空的JSON文件中
【发布时间】:2021-04-09 21:39:13
【问题描述】:

我已经有一个使用 Python 2.7 解析的 JSON 文件,我想将解析出的数据转储到另一个空的 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 字符串?将所有内容处理成一个列表,然后 json.dump 该列表。
  • @tdelaney 我已编辑问题以显示新 JSON 文件的示例。我只想在解析数据时追加以节省时间

标签: python arrays json python-2.7


【解决方案1】:

您正在读取和写入单个 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 2012-11-20
    • 1970-01-01
    • 2020-11-10
    • 2012-03-21
    • 1970-01-01
    • 2015-05-12
    相关资源
    最近更新 更多