python中如何快速删json文件中指定的数据

自然
  • 16

321.png
如图所示,要如何一次性删除所有的
"explanation":与 "more":
其它的保留

json = open(r'./word.json', 'r')

评论
阅读 1.6k
3 个回答
✓ 已被采纳
with open(r'./word.json', "r", encoding="utf-8") as f:
    json_data = json.load(f)
    list1= []
    for i in json_data:
        i.pop("explanation")
        i.pop("more")
        list1.append(i)

with open(r'./word.json', "w", encoding="UTF-8") as e:
    json_new_data = json.dumps(list1, ensure_ascii=False, indent=4)
    e.write(json_new_data)

可以试下不解析,直接读文件,删除 "explanation":与 "more" 行的内容

解析一下也不会太慢

import json  
with open("word.json","r+") as file:  
    txt = json.load(file)  
    for it in txt:  
        for key in ["explanation","more"]:  
            if it.__contains__(key):  
                it.__delitem__(key)  
  
    file.seek(0,0)  
    json.dump(txt,file)  
    file.truncate(file.tell())
撰写回答

登录后参与交流、获取后续更新提醒

宣传栏