【发布时间】:2021-11-27 07:06:16
【问题描述】:
我正在尝试将数据从 SQL 移动到 Mongo。这是我面临的一个挑战,如果任何子对象为空,我想删除父元素。我想直到保险字段被删除。
这是我尝试过的:
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
样本数据
{
"_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",
}
}
结果应该是这样的
{
"_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",
}
}
【问题讨论】:
-
你能把正确处理后的样本结果给我看看吗
-
“保险”以下的所有内容(如果为空)或包括“保险”在内的所有内容都将被删除?
-
是的,这是正确的@BrutusForcus,如果下面的所有子元素都为空,则应删除保险。您好还更新了 json 以显示结果
标签: python json python-3.x mongodb