How to delete entire JSON entry if the value is not found in other keys using jq in Powershell?

Viewed 90
{
    "openapi": "3.0.1",
    "paths": {
        "/api/car": {
            "summary": "Something about Duration"
        },
        "/api/plane": {
            "summary": "Something about Duration"
        }
    },
    "components": {
        "schemas": {
            "Duration": {
                "enum": [
                    "OneMonth",
                    "ThreeMonth"
                ]
            },
            "Apple": {
                "type": "object",
                "properties": {
                    "flaggedDataCount": {
                        "type": "integer",
                        "description": "someting",
                        "format": "int32"
                    }
                }
            }
        }
    }
}

I have a JSON entry above. I want to delete any JSON entry in schemas, which is not found in paths values recursively.

For example, Duration is found in the values at paths, but not for Apple.

So Apple entry should be deleted from the JSON file.

How do I do it with jq in Powershell?

I have thought of the codes below but I do not know:

  • walk from components
  • count the key value in the rest of JSON file at the test

walk(if type == "object????" then with_entries(select(.key | test("?????") | not)) else . end)

1 Answers

You're right about the relevance of the with_entries(select(...)) idiom:

[.paths[].summary] as $texts
| .components.schemas |=
    with_entries( select( .key as $key | any($texts[]; index($key) )))
Related