Home > database >  How can I remove a json element from a list without removing the whole list?
How can I remove a json element from a list without removing the whole list?

Time:12-24

This is my json file:

{"dates" : ["15-12-2021", "16-12-2021", "17-12-2022"]}

Here is my code:

with open(path_to_json_file, 'r') as jsonf: 
   data = json.load(jsonf)
   data_ = data['dates']
   for date in data_:
       imgs_to_delete.append(dates)
       #I want to remove here date from the json file

After I saved the date variable in my list, I want to remove it from the json file.

e.g.: I only want to remove "16-11-2021" from the json file. How can I do this.

CodePudding user response:

To delete element from list you can do

data_.remove("your date to delete")

However if you do that during iterate over list you can get weird results. You should iterate over copy of it or store elements to delete in another list to remove elements at the end. The simplest could be first solution:

   for date in data_[:]:
       data_.remove("your date")

At the end write content of data into json file.

  • Related