5 回答

TA貢獻(xiàn)1829條經(jīng)驗 獲得超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)

TA貢獻(xiàn)1858條經(jīng)驗 獲得超8個贊
作為一般經(jīng)驗法則,您通常不想在迭代可迭代對象時對其進(jìn)行更改。我建議你在第一個循環(huán)中保存你想要的元素:
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, ...)

TA貢獻(xiàn)1877條經(jīng)驗 獲得超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”,我只是把它放在那里,這樣打印時看起來更易讀。

TA貢獻(xiàn)1812條經(jīng)驗 獲得超5個贊
這將創(chuàng)建一個新列表,并僅將那些沒有的列表分配"name": "my_script.py"
到新列表中。
obj = [i for i in obj if i["name"] != "my_script.py"]
添加回答
舉報