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??
You can traverse to .file and .dev at once using .source | .file, .dev or .source["file", "dev"], then filter out null values using values (not ?).
map(.source | .file, .dev | values)
# or
map(.source["file", "dev"] | values)
[
"test",
"foo"
]
Instead of using ? or other operators, using getpath/1 is one option, where you can just filter paths and get their value
[ getpath(paths | select(.[-1] == "file" or .[-1] == "dev")) ]
Or 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With