【发布时间】: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