简体   繁体   中英

Find first json object with given key name recursively using jq

How can I find recursively first key with given name using jq?

Suppose I have JSON structure:

{
  "firstKey": { 
      "secondKey": {
          "model": {
              "name": {
                  ....
               } 
           }
       }
   }
}   

Is there any way how to tell jq to return me first found json object with key name for example in this case "model"? So it returns:

"model": {
    "name:" {
      ....
    } 
}

To select just the first, use first :

first(.. | objects | select(has("model")))

or if minimizing keystrokes is a goal:

first(..|select(.model?))

Or, if your input has more than one top-level JSON document, and you only want at most one from the bunch:

jq -n 'first(inputs|..|select(.model?))'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM