Consider the following file.json
where "x"
is a known string. Two questions:
-
I want to obtain a list of all the unique values in the child arrays. What I have is
jq -r '.x[][] file.json | sort | uniq
. Is there a native solution? -
I want to choose keys
"a"
and"c"
based on the fact that they both have"3"
in their respective child arrays. How do I go about that? I can get the child arrays with"3"
in them withjq -r '.x[] | select(index("3") >= 0)' file.json
but I need access to the parent key.
{
"x": {
"a": [
"2",
"3"
],
"b": [
"1",
"2"
],
"c": [
"3",
"4"
]
}
}
3
Answers
jq -r '.x | with_entries(select(.value | index("3"))) | keys[]'
seems to do the trick.For the first, getting the unique values of the child arrays:
or if you want the results one element per line instead of as JSON:
Yes, jq has its own
unique
filter (which also sorts its input automatically). Collect all the items with[…]
into a single array before using it.Demo
You could iterate over the (sorted)
keys
(usekeys_unsorted
instead if you want the original order), and useIN
(which is just a shortcut toany
using==
as comparator) toselect
by containedness.Demo