5 回答
![?](http://img1.sycdn.imooc.com/545863e80001889e02200220-100-100.jpg)
TA贡献1829条经验 获得超9个赞
import json
with open('my_file.json') as f:
data = json.load(f)
data = [item for item in data if item.get('name') != 'my_script.py']
with open('output_my_file.json', 'w') as f:
json.dump(data, f, indent=4)
![?](http://img1.sycdn.imooc.com/533e50ed0001cc5b02000200-100-100.jpg)
TA贡献1858条经验 获得超8个赞
作为一般经验法则,您通常不想在迭代可迭代对象时对其进行更改。我建议你在第一个循环中保存你想要的元素:
import json
with open('path/to/file', 'r') as f:
data = json.load(f)
items_to_keep = []
for item in data:
if item['name'] != 'my_script.py':
items_to_keep.append(item)
with open('path/to/file', 'w') as f:
json.dump(items_to_keep, f, ...)
过滤可以简化为一行(称为列表理解)
import json
with open('path/to/file', 'r') as f:
data = json.load(f)
items_to_keep = [item for item in data if item['name'] != 'my_script.py']
with open('path/to/file', 'w') as f:
json.dump(items_to_keep, f, ...)
![?](http://img1.sycdn.imooc.com/54584e1f0001bec502200220-100-100.jpg)
TA贡献1877条经验 获得超1个赞
尝试:
import json
json_file = json.load(open("file.json"))
for json_dict in json_file:
json_dict.pop("name",None)
print(json.dumps(json_file, indent=4))
你不需要最后一行“json.dumps”,我只是把它放在那里,这样打印时看起来更易读。
![?](http://img1.sycdn.imooc.com/533e4c5600017c5b02010200-100-100.jpg)
TA贡献1812条经验 获得超5个赞
这将创建一个新列表,并仅将那些没有的列表分配"name": "my_script.py"
到新列表中。
obj = [i for i in obj if i["name"] != "my_script.py"]
添加回答
举报