3 回答
TA贡献1866条经验 获得超5个赞
您的示例输入json在每一行上显示一个对象。
所以我的解决方案读取每一行并将其转换为python dict(使用json.loads()),从dict(使用dict.pop()如果键不存在静默失败)中删除所需的键并将其转换回字符串(使用json.dumps()),然后将其写入新文件。
import json
infile = "failure.json"
outfile = "failure1.json"
key = '_id'
with open(infile) as f_read:
with open(outfile, 'w') as f_write:
for line in f_read:
line = line.strip()
if len(line) > 0:
try:
elem = json.loads(line)
elem.pop(key, None)
f_write.write('{}\n'.format(json.dumps(elem)))
except json.JSONDecodeError:
pass
编辑:json根据 OP 的评论,显然每一行都应该进入一个单独的新文件。可以这样做,例如:
import json
infile = "failure.json"
key_to_remove = '_id'
with open(infile) as f_read:
for line in f_read:
line = line.strip()
if len(line) > 0:
try:
elem = json.loads(line)
elem.pop(key_to_remove, None)
outfile = '{}.json'.format(elem['name']) # this may raise KeyError
with open(outfile, 'w') as f_write:
f_write.write('{}\n'.format(json.dumps(elem)))
except json.JSONDecodeError:
pass
TA贡献1796条经验 获得超7个赞
对于删除,你可以使用这样的东西:
import json
import sys
import re
import fileinput
with open('failure.json') as data_file:
data = json.load(data_file)
del data['_id']
with open('failure2.json', 'w') as data_file:
data = json.dump(data, data_file)
并且为了创建具有 id 值的文件,只需解析data对象和id节点值
TA贡献1784条经验 获得超2个赞
您已导入该json
包,但并未使用它。你应该,这很棒。
从文件中获取字符串,然后用于json.loads()
将字符串加载到 json 对象中。从那里,您可以使用 .json 获取 json 对象的每个元素for key in json_object
。
添加回答
举报