首页 > 解决方案 > 使用 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
        ]
      }
    ]
  ]
}

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

[
      "create",
      "w51",
      "rwt.widgets.Label",
      {
        "parent": "w41",
        "style": [
          "NONE"
        ],
        "bounds": [
          101,
          0,
          49,
          42
        ],
        "tabIndex": -1,
        "customVariant": "variant_pufferLabelLogout"
      }
]

标签: jsonjq

解决方案


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

.operations[]
| select( index("w51") )

备择方案

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

.operations[] | select( any(. == "w51" ) )

推荐阅读