Jay Park
Jay Park

Reputation: 348

How to delete particular field in a json file by using python

1.I was trying to use python to delete a particular key and its value in a JSON file. Here is the JSON file structure:

[
  {
    "_id": {
      "$oid": "6066af7bcb0716461578fa70"
    },
    "FileName": "copy_of_ex_fts.csv",
    "BriefInfo": "",
    "Size": "13.532KB",
    "UserName": "12795757"
    "data":"123"
  }
]

I wrote some code to remove key "data" and "UserName" with their values but I only can remove the data and its value not for the "UserName". Can someone give me some suggestions for fixing this bug?

2.Here is the code for implementation. Firstly just open the JSON file and load the data. Then to check if the key "data" and "UserName" are in it or not. If yes, delete these keys and their value.

jsonFile = open('./dataNewJson.json', 'r')
    values = json.load(jsonFile)
    for element in values:
        if 'data' in element:
            del element['data']
            print("check")
        elif 'BriefInfo' in element:
            del element['BriefInfo']
        elif 'UserName' in element:
            print("SSS")
            del element['UserName']
    values = dumps(values, indent = 2)

Upvotes: 4

Views: 12346

Answers (1)

MalcolmInTheCenter
MalcolmInTheCenter

Reputation: 1605

 for element in values:     
     if 'data' in element:     
         del element['data']     
         print("check")     
     if 'BriefInfo' in element:     
         del element['BriefInfo']     
     if 'UserName' in element:     
         print("SSS")     
         del element['UserName']     

elif needs to be if. on each iteration data is found first so it falls into that if statement and skips the others.

Upvotes: 6

Related Questions