更新用Python编辑的json文件

2024-10-02 10:34:26 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个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
    },
    {
      "name": "abc",
      "marks": 78
    }
  ],
  "course_id": "567",
  "s_name": "abc public school"
}

这是一个单一的对象。有数百种类似的物体。 我所做的是从“名称列表”中访问每个“名称”,并使用一些规则清理它。在这个过程中,一些常见的名字被删除了。 现在我想将清理后的数据更新回json文件。请注意,如果过滤了公共名称,则在将数据更新回json文件时,也应删除相应的标记。 有人能帮我吗? 我将这些json对象放在一个文件中,我使用“smart_open”库打开了这个文件


Tags: 文件数据对象name名称idjsonlist
1条回答
网友
1楼 · 发布于 2024-10-02 10:34:26

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

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

相关问题 更多 >

    热门问题