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

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

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

阅读 12k
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())
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏