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

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

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

阅读 894
评论 2月29日提问
    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)
    评论 赞赏
      Lin_R
      • 5.2k

      可以试下不解析,直接读文件,删除 "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())
        评论 赞赏
          撰写回答

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