Shang Jian Ding
Shang Jian Ding

Reputation: 2126

select all keys with given value

With jq, how do I select all objects, which may be nested, with a desired value?

For example, given the following:

{
    "a": "b",
    "c": {
        "d": {
            "e": "f",
            "z": "b"
        }
    }
}

How do I filter down to objects whose value is "b"?

{
    "a": "b",
    "c": {
        "d": {
            "z": "b"
        }
    }
}

Conversely, how do I select objects whose value is not "b"?

{
    "c": {
        "d": {
            "e": "f"
        }
    }
}


I've attempted at the problem by using the select and walk functions, but could not get exactly what I wanted.

Upvotes: 1

Views: 70

Answers (1)

peak
peak

Reputation: 116650

For the first question:

reduce paths(. == "b") as $p ({}; setpath($p; "b"))

For the second:

reduce paths(. == "b") as $p (.; delpaths([$p]))

or even more succinctly:

delpaths( [ paths(. == "b") ] )

Furthermore

The first question can also be answered without reduce, but to get it right generically requires more verbosity, e.g.:

delpaths( [ paths( (. !="b") and (type|IN("object","array") | not) ) ] )

Upvotes: 2

Related Questions