正在动态路径中查找要从JSON中移除的元素

jjjwad0x  于 2023-03-20  发布在  其他
关注(0)|答案(2)|浏览(87)

如果您有一些JSON,其中包含未知路径,例如

...... {
                        "in": "query",
                        "name": "@baseType",
                        "type": "string",
                        "description": "To route object models\nValues: \xxx\uyyy or \xxx\zzzd"
                    },
                    {
                        "in": "header",
                        "name": "X-System",
                        "type": "string",
                        "default": "Inventory: Inventory\\nFor Quickconnect: My Resourse"
                    },
                    {
                        "in": "header",
                        "name": "env",
                        "type": "string",
                        "default": "Environment, i.e: a01, b02, etc."
                    }

我需要删除所有默认行,其中"in": "header"
但就我而言,我不知道所有可能发生的路径。有什么想法吗?
如果我知道路径,那么这相对容易。

for get_param_rec in api_spec['paths']['/resource']['get']['parameters']:
            if get_param_rec['in'] == "header" and "default" in get_param_rec:
                logger.info("      found bad header record and deleting it.")
                del get_param_rec['default']
gab6jxml

gab6jxml1#

可以使用递归函数迭代JSON字典:

import json

def remove_default(obj):
    if isinstance(obj, dict):
        if obj.get('in') == 'header':
            print('found bad header record and deleting it.')
            obj.pop('default', None)
        for v in obj.values():
            remove_default(v)
    elif isinstance(obj, list):
        for v in obj:
            remove_default(v)

with open('input.json') as f:
    obj = json.load(f)

remove_default(obj)
print(json.dumps(obj, indent=2))

input.json

{
  "inner1": {
    "inner2": [
      {
        "in": "query",
        "name": "@baseType",
        "type": "string",
        "description": "To route object models",
        "default": "keep it"
      },
      {
        "in": "header",
        "name": "X-System",
        "type": "string",
        "default": "Inventory: Inventory"
      },
      {
        "in": "header",
        "name": "env",
        "type": "string",
        "default": "Environment, i.e: a01, b02, etc."
      }
    ]
  }
}

output
一个二个一个一个

eqqqjvef

eqqqjvef2#

您可以使用递归函数,根据每个深度级别的条件删 debugging 误记录。将每个子指令规范化为一系列值,以便您可以使用与子列表相同的方式迭代其子记录:

def remove_bad_records(obj):
    values = ()
    if isinstance(obj, dict):
        if obj['in'] == 'header':
            obj.pop('default', None)
        values = obj.values()
    elif isinstance(obj, list):
        values = obj
    for value in values:
        remove_bad_records(value)

演示:https://replit.com/@blhsing/DefensiveMadeupService

相关问题