How to delete an object in . json using Python?

Asked

Viewed 267 times

0

I use an Excel processing system, which uses Python to make most of its features.

I’m having a hard time in this situation: I want to edit a file. json using Python, in particular, I want to delete one of my "Schedule" by updating its respective number. All the times I tried it never worked. Here’s a photo from the file. json and the Python code I use to add and clean the file respectively.

Esse é o arquivo .json que quero manipular

Esse é o código em Python que uso para adicionar e apagar todos

Example: In the . json file, I want to delete from the comma on line 32 until before the comma on line 39. (if possible update the numbers of each "schadule")

Note: Depending on the project, this file . json has more than 400 "schadule".

If I open . json and manually delete what I want, it works fine. I just want to find a way to erase a part of it in case I miss, through a button.

1 answer

1


You can create a function that deletes a 'Schedule' by identifier. In your example, you point the lines [33-39] to delete, which is represented by the key/identifier "6". So, just do a function that given an identifier you remove that identifier from the file. To handle json vc files you can use the python json module. When opening and loading the file with the json module, the function should delete the identifier passed. Ex:

def delete_schedule(key):
    with open("seu_nome_de_arquivo.json", "r") as file:
        data = json.load(file)
        delete data["schedule"][key]
    with open('data.txt', 'w') as file:
        json.dump(data, file)

I used this as a base link

Browser other questions tagged

You are not signed in. Login or sign up in order to post.