Json 让jq返回数组中元素的索引号

Json 让jq返回数组中元素的索引号,json,jq,Json,Jq,我希望jq返回基于搜索的数组中某个元素的索引 使用下面的数组,我调用jq来查找键的值“FooBar”“text”: 但我真正想要的是嵌套这对text:FooBar的最外层数组“arr”的索引,在本例中为0 这能在jq中实现吗 { "arr": [ [ "create", "w71", "rwt.widgets.Label", { "parent": "w68", "style": "1", "

我希望jq返回基于搜索的数组中某个元素的索引

使用下面的数组,我调用jq来查找键的值
“FooBar”
“text”:

但我真正想要的是嵌套这对
text:FooBar
的最外层数组
“arr”
的索引,在本例中为0

这能在jq中实现吗

{
"arr": [
    [
      "create",
      "w71",
      "rwt.widgets.Label",
      {
        "parent": "w68",
        "style": "1",
        "bounds": "2",
        "tabIndex": -1,
        "background": "ww",
        "font": "test",
        "text": "FooBar",
        "alignment": "right"
      }
    ],
    [
          "create",
          "w72",
          "rwt.widgets.Label",
          {
            "parent": "w68",
            "style": "22",
            "bounds": "1",
            "tabIndex": -1,
            "foreground": "null",
            "background": "1",
            "font": "2",
            "text": "55",
            "alignment": "right"
          }
        ]
  ]
}

您可以首先将数组中的元素转换为条目,这样键和值都会出现在输出中:

jq '.arr | to_entries'
[
  {
    "key": 0,
    "value": [
      "create",
      "w71",
      "rwt.widgets.Label",
      {
        "parent": "w68",
        "style": "1",
        "bounds": "2",
        "tabIndex": -1,
        "background": "ww",
        "font": "test",
        "text": "FooBar",
        "alignment": "right"
      }
    ]
  },
  {
    "key": 1,
    "value": [
      "create",
      "w72",
      "rwt.widgets.Label",
      {
        "parent": "w68",
        "style": "22",
        "bounds": "1",
        "tabIndex": -1,
        "foreground": "null",
        "background": "1",
        "font": "2",
        "text": "55",
        "alignment": "right"
      }
    ]
  }
]
如果输出中存在
,则给出结果:

jq '.arr | to_entries'
[
  {
    "key": 0,
    "value": [
      "create",
      "w71",
      "rwt.widgets.Label",
      {
        "parent": "w68",
        "style": "1",
        "bounds": "2",
        "tabIndex": -1,
        "background": "ww",
        "font": "test",
        "text": "FooBar",
        "alignment": "right"
      }
    ]
  },
  {
    "key": 1,
    "value": [
      "create",
      "w72",
      "rwt.widgets.Label",
      {
        "parent": "w68",
        "style": "22",
        "bounds": "1",
        "tabIndex": -1,
        "foreground": "null",
        "background": "1",
        "font": "2",
        "text": "55",
        "alignment": "right"
      }
    ]
  }
]
执行筛选并返回索引将变得相当简单:

jq '.arr | to_entries | .[] | select(.value[3].text | contains("FooBar")) | .key' <test.json

jq'.arr | to_entries |.[]| select(.value[3]。text | contains(“FooBar”))|。key'这里有一个解决方案,它不依赖于感兴趣的对象在数组中具有固定位置的假设:

.arr
| map( .[] | objects | .text ) 
| index("FooBar")
更有力地:

.arr 
| map( first(.[] | objects) // null | .text )
| index("FooBar")

令人惊叹的!非常感谢。但是,我必须通过管道传递
到字符串
,因为我忘了在示例数组中放入没有
text
键的元素,因此返回null。