Skip to content
Advertisement

Updating the json file edited in Python

Suppose I have a json file like –

{
  "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"
}

This is a single object. There are hundreds of objects similar to these. What i did was I accessed every ‘name’ from “name_list” and cleaned it using some rules. In that process some common name were removed. Now I want to update the cleaned data back to the json file. Note that if the common name is filtered then while updating the data back to json file the corresponding marks should also be removed. Can someone help me out on this? I have these json objects in a single file, which I opened using ‘smart_open’ library.

Advertisement

Answer

Let me show you with an example how you can do this:

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
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement