【问题标题】:How to remove parent json element in python3 if child is object is empty如果子对象为空,如何在python3中删除父json元素
【发布时间】: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


【解决方案1】:

您的 if 语句有点令人困惑。我认为您正在寻找递归:

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))

编辑/注意:从 Python3.8 开始,您可以在推导中使用赋值 (:=)

输出:

{
    "_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"
    }
}

【讨论】:

  • 不客气!我只是修改了代码以避免在理解中调用该函数两次。仅适用于 python 3.8 或更高版本...
【解决方案2】:

试试这个:

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)

输出:

{
    '_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'
    }
}

【讨论】:

  • 感谢您这么快恢复。无论如何,我正在寻找更通用的功能。
猜你喜欢
  • 1970-01-01
  • 2019-10-05
  • 2012-08-06
  • 2022-08-10
  • 2019-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多