Search code examples
pythonjson

How to i delete mutiple elements of json file on python


I am trying to delete mutiple information of a json file but I dont know what to do in python to resolve the problem

I tried add() it doesnt work and pop() and i can't make it to work either so what other option is their that I can try


Solution

  • Wondering, if you tried using "del" keyword.

    1. Load the json data into a dictionary "data".
    2. Delete the key-value pairs for keys you want to delete.
    3. Save the new dictionary data into a new json file.

    Sample code -

    import json
    
    with open('data_file.json', 'r') as file:
       data = json.load(file)
    
    keys_to_delete = ['k1', 'k2', 'k3']
    for k in keys_to_delete:
       if k in data:
          del data[k]
    
    with open('new_data.json', 'w') as file:
       json.dump(data, file)