4

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)
0

1 Answer 1

6
 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.