I have this sort of json:
[
{
"source":
{
"file": "test",
"baz": "now"
}
},
{
"source": {
"dev": "foo"
}
},
{
"source": {
"bar": "bar"
}
}
]
and I would like to get a list of all values for file
or dev
. So the expected outcome of the above should be: ["test", "foo"]
I am stuck somewhere here:
.[].source | select(.file? or .dev?)
But that yield the complete objects. How to access only the attribute values than??
2
Answers
Instead of using
?
or other operators, usinggetpath/1
is one option, where you can just filter paths and get their valueOr even combine with another condition to check for
source
key, if you want to be completely sure i.e..[-2] == "source"
Demo – https://jqplay.org/s/IddhVIbUenj
You can traverse to
.file
and.dev
at once using.source | .file, .dev
or.source["file", "dev"]
, then filter out null values usingvalues
(not?
).