【问题标题】:Remove JSON element on loop in Python在 Python 中删除循环中的 JSON 元素
【发布时间】:2023-03-16 19:44:01
【问题描述】:

我有这个 JSON

{"data": 
    [   
        {   
            "id": "11111", 
            "description": "Description 1", 
            "to_remove": "blah",
            "state": "Assigned"
        },
        {   
            "id": "2222", 
            "description": "Description 2",         
            "to_remove": "blah"
        },
        {   
            "id": "33333", 
            "description": "Description 3", 
            "to_remove": "blah",
            "state": "Assigned"
        }
]}

我需要删除“状态”不存在的所有对象并删除单个键 (to_remove) 才能获得此输出:

{"data": 
    [   
        {   
            "id": "11111", 
            "description": "Description 1", 
            "state": "Assigned"
        },
        {   
            "id": "33333", 
            "description": "Description 3", 
            "state": "Assigned"
        }
]}

我尝试使用此代码:

      json_data = json.loads(data)

      for element in json_data['data']:
          if 'state' in element:
             del element['to_remove']   
          else:
             del element

但是输出是这样的:

{"data": 
    [   
        {   
            "id": "11111", 
            "description": "Description 1", 
            "state": "Assigned"
        },
        {   
            "id": "2222", 
            "description": "Description 2"          
            "to_remove": "blah",
        },
        {   
            "id": "33333", 
            "description": "Description 3", 
            "state": "Assigned"
        }
]}

我可以删除单个键,但不能删除所有元素。 del 元素 命令不返回错误。 如果我在 del 元素 之后使用 del 元素['to_remove'] 我有错误“名称元素不存在”

【问题讨论】:

    标签: python json element


    【解决方案1】:

    del element 只是unbinds the loop variable element。这不会影响对同一对象的任何其他引用。它不会将其从列表中删除。如果是这样,您将在迭代列表时从列表中删除which is also bad

    相反,按照以下几行重建列表:

    data = []
    for element in json_data['data']:
        if 'state' in element:
            del element['to_remove']   
            # more robust: element.pop('to_remove', None)
            data.append(element)
    json_data['data'] = data
    

    【讨论】:

      猜你喜欢
      • 2019-02-09
      • 2020-06-02
      • 2015-05-23
      • 1970-01-01
      • 2014-05-03
      • 2012-02-15
      • 2011-12-31
      • 2013-05-04
      • 1970-01-01
      相关资源
      最近更新 更多