Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
Cómo eliminar el elemento json principal en python3 si el objeto secundario está vacío

Estoy tratando de mover datos de SQL a Mongo. Aquí hay un desafío al que me enfrento, si algún objeto secundario está vacío, quiero eliminar el elemento principal. Quiero que se elimine el campo de seguro.

Esto es lo que probé:

 def remove_empty_elements(jsonData): if(isinstance(jsonData, list) or isinstance(jsonData,dict)): for elem in list(jsonData): if not isinstance(elem, dict) and isinstance(jsonData[elem], list) and elem: jsonData[elem] = [x for x in jsonData[elem] if x] if(len(jsonData[elem])==0): del jsonData[elem] elif not isinstance(elem, dict) and isinstance(jsonData[elem], dict) and not jsonData[elem]: del jsonData[elem] else: pass return jsonData

Data de muestra

 { "_id": "30546c62-8ea0-4f1a-a239-cc7508041a7b", "IsActive": "True", "name": "Pixel 3", "phone": [ { "Bill": 145, "phonetype": "xyz", "insurance": [ { "year_one_claims": [ { "2020": 200 }, { }, { }, { }, { } ] }, { "year_two_claims": [ { }, { }, { }, { }, { } ] }, ] } ], "Provider": { "agent": "aaadd", } }

Los resultados deberían verse así

 { "_id": "30546c62-8ea0-4f1a-a239-cc7508041a7b", "IsActive": "True", "name": "Pixel 3", "phone": [ { "Bill": 145, "phonetype": "xyz", "insurance": [ { "year_one_claims": [ { "2020": 200 }, ] }, ] } ], "Provider": { "agent": "aaadd", } }
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Tus declaraciones if son un poco confusas. Creo que estás buscando una recursividad:

 import json # define which elements you want to remove: to_be_deleted = [[], {}, "", None] def remove_empty_elements(jsonData): if isinstance(jsonData, list): jsonData = [new_elem for elem in jsonData if (new_elem := remove_empty_elements(elem)) not in to_be_deleted] elif isinstance(jsonData,dict): jsonData = {key: new_value for key, value in jsonData.items() if (new_value := remove_empty_elements(value)) not in to_be_deleted} return jsonData print(json.dumps(remove_empty_elements(jsonData), indent=4))

Editar/Nota: desde Python3.8 puede usar asignaciones ( := ) en comprensiones

Producción:

 { "_id": "30546c62-8ea0-4f1a-a239-cc7508041a7b", "IsActive": "True", "name": "Pixel 3", "phone": [ { "Bill": 145, "phonetype": "xyz", "insurance": [ { "year_one_claims": [ { "2020": 200 } ] } ] } ], "Provider": { "agent": "aaadd" } }
over 4 years ago · Santiago Trujillo Relatório

0

Prueba esto:

 data = { "_id": "30546c62-8ea0-4f1a-a239-cc7508041a7b", "IsActive": "True", "name": "Pixel 3", "phone": [ { "Bill": 145, "phonetype": "xyz", "insurance": [ { "year_one_claims": [ { "2020": 200 }, { }, { }, { }, { } ] }, { "year_two_claims": [ { }, { }, { }, { }, { } ] }, ] } ], "Provider": { "agent": "aaadd", } } for phn_data in data['phone']: for ins in phn_data['insurance']: for key, val in list(ins.items()): for ins_data in list(val): if not ins_data: val.remove(ins_data) if not val: del ins[key] phn_data['insurance'].remove(ins) print (data)

Producción:

 { '_id': '30546c62-8ea0-4f1a-a239-cc7508041a7b', 'IsActive': 'True', 'name': 'Pixel 3', 'phone': [{ 'Bill': 145, 'phonetype': 'xyz', 'insurance': [{ 'year_one_claims': [{ '2020': 200 }] }] }], 'Provider': { 'agent': 'aaadd' } }
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda