更新Python中编辑的json文件

问题描述

假设我有一个像 -

这样的 json 文件
{
  "course": "hwjxh","school_id": 1234,"name_list": [
    {
      "name": "xyzzy","marks": 97
    },{
      "name": "abc","marks": 44
    },{
      "name": "qwe","marks": 78
    },{
      "name": "def","marks": 90
    },{
      "name": "jkl","marks": 80
    },"marks": 78
    }
  ],"course_id": "567","s_name": "abc public school"
}

这是一个单一的对象。有数百个与这些类似的对象。 我所做的是访问“name_list”中的每个“名称”并使用一些规则对其进行清理。在那个过程中,一些常用名称删除了。 现在我想将清理后的数据更新回 json 文件。请注意,如果公共名称被过滤,那么在将数据更新回 json 文件时,也应删除相应的标记。 有人可以帮我解决这个问题吗? 我将这些 json 对象放在一个文件中,我使用“smart_open”库打开了该文件

解决方法

让我用一个例子向你展示如何做到这一点:

import json

def check_name(name):
    if 'xyz' in name: #define the name filter here,this example filters out names with xyz
        return False
    #elif 'something' in name: #optionally more filters
    #    return False
    else:
        return True

with open("filename.json") as f:
    data = json.load(f) #load json as python dictionary
    data['name_list'] = [i for i in data['name_list'] if check_name(i['name'])] #pass the name_list items to the filter function and keep only those items that return True
    json.dump(data,open("filename.json","w")) #save back to json