简体   繁体   English

使用jq递归查找第一个具有给定键名的json对象

[英]Find first json object with given key name recursively using jq

How can I find recursively first key with given name using jq? 如何使用jq递归查找具有给定名称的第一个键?

Suppose I have JSON structure: 假设我具有JSON结构:

{
  "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"? 有什么方法可以告诉jq返回我第一次找到的带有键名的json对象,例如在这种情况下为“模型”? So it returns: 因此它返回:

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

To select just the first, use first : 要仅选择第一个,请使用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: 或者,如果您的输入包含多个顶级JSON文档,而您最多只希望其中一个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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