使用jq通过包含字符串查找数组元素

tzi*_*ppy 1 json jq

我有一个数组“操作”,我想从中返回包含匹配字符串的所有元素,如"w51". 到目前为止,我发现的所有样本都涉及键值对。我正在使用jq '.operations[]' < file检索元素。

{
  "operations": [
    [
      "create",
      "w51",
      "rwt.widgets.Label",
      {
        "parent": "w41",
        "style": [
          "NONE"
        ],
        "bounds": [
          101,
          0,
          49,
          42
        ],
        "tabIndex": -1,
        "customVariant": "variant_pufferLabelLogout"
      }
    ],
    [
      "create",
      "w39",
      "rwt.widgets.Composite",
      {
        "parent": "w34",
        "style": [
          "NONE"
        ],
        "children": [
          "w52"
        ],
        "bounds": [
          0,
          42,
          762,
          868
        ],
        "tabIndex": -1,
        "clientArea": [
          0,
          0,
          762,
          868
        ]
      }
    ]
  ]
}
Run Code Online (Sandbox Code Playgroud)

搜索包含“w51”的数组元素时,我的预期输出是这样的:

[
      "create",
      "w51",
      "rwt.widgets.Label",
      {
        "parent": "w41",
        "style": [
          "NONE"
        ],
        "bounds": [
          101,
          0,
          49,
          42
        ],
        "tabIndex": -1,
        "customVariant": "variant_pufferLabelLogout"
      }
]
Run Code Online (Sandbox Code Playgroud)

pea*_*eak 7

如果您使用 jq 1.4 或更高版本,以下内容应该会产生所需的输出:

.operations[]
| select( index("w51") )
Run Code Online (Sandbox Code Playgroud)

备择方案

有很多替代方案,具体取决于您拥有的 jq 版本。如果您的 jq 有any/0,则以下是一个有效的选择:

.operations[] | select( any(. == "w51" ) )
Run Code Online (Sandbox Code Playgroud)