How to delete a json object with python?

Asked

Viewed 129 times

-4

data = ler_repositorio()
print (data)
excluir_funcionrio = input('quem você quer excluir: ')

print('Tem certeza?')
print('1 - continuar')
print('2 - voltar')
opção_adquirida = int(input('Escolha: '))

if opção_adquirida == 1:
    for funcionario in data:
        if funcionario == excluir_funcionrio:

            print (funcionario)


elif opção_adquirida == 2:
    pass

I prescribe to delete an object, in this case exclude an employee.

2 answers

0

I would do it this way:

excluir_funcionrio = input('quem você quer excluir: ')

print('Tem certeza?')
print('1 - continuar')
print('2 - voltar')

if opção_adquirida == 1:
   for funcionario in enumerate(data):
       if data[funcionario[0]]['nome'] == excluir_funcionário:
          del data[funcionario[0]]

The method enumerate() returns a tuple with the index of the element in the list and the contents of the same list. Therefore, when comparing the employee appointed for exclusion with the current element of the for, position 0 must be reported.

If you give a print(funcionario) within the for, You will see the tuple I reported. Once you know the index of the element you want to delete in the list, just run the delete command. Later, just generate the JSON file again with the new list.

0


If employees are stored on a list, you can try the following:

data = ["João", "Pedro", "Maria"]
print (data)

funcionario_a_excluir = input('Quem quer excluir? ')

print('Tem certeza?')
print('1 - continuar')
print('2 - voltar')
opcao_adquirida = int(input('Escolha: '))

if opcao_adquirida == 1:
    data.remove(funcionario_a_excluir)

print(data)

Behold this question for more information on removing list-specific elements.

  • 1

    +1, Thanks for helping me

Browser other questions tagged

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