Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jq to find array element by containing string

Tags:

json

jq

I have an array "operations" from which I would like to return all the elements that contain a matching string like "w51". Until now, all the samples I have found dealt with key value pairs. I am using jq '.operations[]' < file to retrieve the elements.

{
  "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
        ]
      }
    ]
  ]
}

My expected output when searching for an array element that contains "w51" would be this:

[
      "create",
      "w51",
      "rwt.widgets.Label",
      {
        "parent": "w41",
        "style": [
          "NONE"
        ],
        "bounds": [
          101,
          0,
          49,
          42
        ],
        "tabIndex": -1,
        "customVariant": "variant_pufferLabelLogout"
      }
]
like image 237
tzippy Avatar asked Sep 05 '25 03:09

tzippy


1 Answers

If you use jq version 1.4 or later, the following should produce the desired output:

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

Alternatives

There are many alternatives, depending on which version of jq you have. If your jq has any/0, the following is an efficient option:

.operations[] | select( any(. == "w51" ) )
like image 162
peak Avatar answered Sep 07 '25 21:09

peak