skip to Main Content

I have a JSON file and I want to make a counter that every time the day (day = lastday - today) (lastday is the day that the counter will stop and the day will be 0) is 0 then I should remove the specific dictionary from the JSON file from where the dictionaries day will be 0.

I succesfully made the counter but I don’t know how to make it remove the specific dictionary from the JSON file. Maybe if I could read where the cursor and in with dicitonary the count day = 0 then all would be better.

Here is the type of JSON file:

[
    {
        "Name": "bla",
        "Lastname": "ftr",
        "date": "20/12/2023"
    },
    {
        "Name": "dfas",
        "Lastname": "fsae",
        "date": "18/12/2023"
    },
    {
        "Name": "john",
        "Lastname": "rapper",
        "date": "18/11/2023"
    }
 ]
import time
from datetime import datetime
import json
import time

def countdown(stop):
    while True:
        difference = stop - datetime.now()
        if difference.days == 0:
            print("Good bye!")
            break
            print("The count is: " + str(difference.days) + " day(s)")
            break

def handling():
    with open('tst.json') as f:    
        data = json.load(f)
        for i in range(len(data)):
          date = data[i]["date"]
          i = i + 1
          x = (datetime.now() - datetime.strptime(date, '%d/%m/%Y')).days
          print(x)
          if x == 0:
                    print("Here i want to remove the dictionary that counts day = 0)

I also tried this but nothing happens:

import json

with open('tst.json') as fin:
    your_structure = json.load(fin)
for value in your_structure:
    p = value.pop("date", None)
    print(p)
    print("all done")

2

Answers


  1. Chosen as BEST ANSWER

    I made it, thanks for the answer but what i needed is:

    def remove():
        with open("/home/dimos/organ/json/tst.json", 'r') as file:
            data = json.load(file)
            date_to_remove = '18/12/2023' #
            update_data = [entry for entry in data if entry.get("date") != date_to_remove]
        with open("/home/dimos/organ/json/tst.json", 'w') as file:
            json.dump(update_data,file,indent = 2)
    

  2. Function handling needs some changes. Code is not tested, so be careful:

       def handling():
            with open('tst.json') as f:    
                data = json.load(f)
                for i in range(len(data) - 1, -1, -1):
                  date = data[i]["date"]
                  # i = i + 1 # Not useful
                  x = (datetime.now() - datetime.strptime(date, '%d/%m/%Y')).days
                  print(x)
                  if x == 0:
                      del data[i]
            
            # data was modified, now it must be saved
            with open('tst.json', 'w') as f:
                json.dump(data, f)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search