Python 删除嵌套键和特定值的键

huangapple go评论68阅读模式
英文:

Python remove nested keys and a certain value's keys

问题

  1. 需要删除任何键的任何级别中具有值为 null 的值
  2. 需要删除名为 key_2.key_c 的任何链接键
    应该得到以下结果块。

原始 JSON

{
  "key_1": {
    "key_a": 111111
  },
  "key_2": {
    "key_a": "value",
    "key_b": null,
    "key_c": {
      "key_c_a": {
        "key_c_b": "value"
      }
    },
    "key_d": [
      {
        "key_c": "value"
      }
    ]
  }
}

结果

{
  "key_1": {
    "key_a": 111111
  },
  "key_2": {
    "key_a": "value",
    "key_d": [
      {
        "key_c": "value"
      }
    ]
  }
}
英文:

1.Need to remove any value in any level of the keys that has a value null
2.Need to remove any chained key that is named key_2.key_c
Should result in the outcome block below.

Original json

{
"key_1": {
    "key_a": 111111},
"key_2": {
    "key_a": "value",
    "key_b": null,
    "key_c": {
        "key_c_a": {
            "key_c_b": "value"}
            },
    "key_d": [{"key_c": "value"}],
}

Outcome

{
"key_1": {
    "key_a": 111111},
"key_2": {
    "key_a": "value",
    "key_d": [{"key_c": "value"}],
}

答案1

得分: 1

你可以通过递归遍历输入的JSON对象并过滤掉不需要的值来实现这一目标:

import json

def filter_json(obj):
    if isinstance(obj, dict):
        new_obj = {}
        for k, v in obj.items():
            if v is None:
                continue
            if k == "key_2":
                new_obj[k] = filter_json({k2: v2 for k2, v2 in v.items() if k2 != "key_c"})
            else:
                new_obj[k] = filter_json(v)
        return new_obj
    elif isinstance obj, list:
        return [filter_json(elem) for elem in obj]
    else:
        return obj

使用:

json_str = '''
{
  "key_1": {
    "key_a": 111111
  },
  "key_2": {
    "key_a": "value",
    "key_b": null,
    "key_c": {
      "key_c_a": {
        "key_c_b": "value"
      }
    },
    "key_d": [
      {
        "key_c": "value"
      }
    ]
  }
}
'''

json_obj = json.loads(json_str)
filtered_obj = filter_json(json_obj)
英文:

You can achieve this by recursively traversing the input JSON object and filtering out the unwanted values:

import json

def filter_json(obj):
    if isinstance(obj, dict):
        new_obj = {}
        for k, v in obj.items():
            if v is None:
                continue
            if k == "key_2":
                new_obj[k] = filter_json({k2: v2 for k2, v2 in v.items() if k2 != "key_c"})
            else:
                new_obj[k] = filter_json(v)
        return new_obj
    elif isinstance(obj, list):
        return [filter_json(elem) for elem in obj]
    else:
        return obj

Usage


json_str = '''
{
  "key_1": {
    "key_a": 111111
  },
  "key_2": {
    "key_a": "value",
    "key_b": null,
    "key_c": {
      "key_c_a": {
        "key_c_b": "value"
      }
    },
    "key_d": [
      {
        "key_c": "value"
      }
    ]
  }
}
'''

json_obj = json.loads(json_str)
filtered_obj = filter_json(json_obj)

huangapple
  • 本文由 发表于 2023年2月18日 00:19:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75486784.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定