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 jsonDataData 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", } }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" } }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' } }