Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jq recursion of unknown levels between two select() filters

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

//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"))) ]

jqplay – Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading