skip to Main Content

If you have some JSON that will contain an unknown path to something like

...... {
                        "in": "query",
                        "name": "@baseType",
                        "type": "string",
                        "description": "To route object modelsnValues: xxxuyyy or xxxzzzd"
                    },
                    {
                        "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."
                    }

I need to delete all the default lines where "in": "header"

but in my case, I have no idea all the paths that could happen. Any ideas?

If I know the path, then this is relatively easy.

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']

2

Answers


  1. You can iterate through the JSON dictionary with a recursive function:

    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:

    found bad header record and deleting it.
    found bad header record and deleting it.
    
    {
      "inner1": {
        "inner2": [
          {
            "in": "query",
            "name": "@baseType",
            "type": "string",
            "description": "To route object models",
            "default": "keep it"
          },
          {
            "in": "header",
            "name": "X-System",
            "type": "string"
          },
          {
            "in": "header",
            "name": "env",
            "type": "string"
          }
        ]
      }
    }
    
    Login or Signup to reply.
  2. You can use a recursive function that removes bad records according to your criteria at each depth level. Normalize each sub-dict to a sequence of values so you can iterate through its sub-records in the same way as a sub-list:

    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)
    

    Demo: https://replit.com/@blhsing/DefensiveMadeupService

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search