given a variable nested json, I would like to filter based on two select functions and return an array of values matching a key.
Is it possible when the recursion between say "dog" and "breed" is unknown and different for multiple branches, but "breed is always a child/grandchild of "dog" in the same json?
I have tried using "objects as a bridge but this does not return a result
//should return ["one","two"]
// tried ....
jq '.. | select(.dog?) | select(.breed?) | .breed' myfile.json
jq '.. | select(.dog?) | objects | select(.breed?) | .breed' myfile.json
jq '.. | objects | select(.dog?) | select(.breed?) | .breed' myfile.json
jq '.. | objects | select(.dog?) | objects | select(.breed?) | .breed' myfile.json
{
"alpha": {
"this": {
"dog": {
"breed": "one",
"colors": {
"eyes": "blue"
}
}
}
},
"beta": {
"dog": {
"crazy": {
"world": {
"breed": "two",
"colors": {
"eyes": "blue"
}
}
}
}
},
"charlie": {
"format": {
"bird": {
"boat": {
"breed": "three",
"colors": {
"eyes": "blue"
}
}
}
}
}
}
>Solution :
You could use getpath/1 function to get root to leaf paths of all the elements in the JSON structure and filter those containing the last path as breed and contains dog somewhere along
[ getpath(paths | select(.[-1] == "breed" and index("dog"))) ]