Reputation: 2126
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
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") ] )
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