我希望jq根据搜索返回数组中元素的索引。
使用下面的数组,我调用jq来找到键"FooBar"
的值"text"
:
jq '.arr[] | .[3].text | tostring | select(contains("FooBar") )' < file.json
结果是:
"FooBar"
但是我真正想要的是嵌套此"arr"
对的最外层数组text:FooBar
的索引,在这种情况下为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"
}
]
]
}
答案 0 :(得分:1)
您可以首先将数组中的元素转换为条目,这样,键和值都将出现在输出中:
jq '.arr | to_entries'
给出输出中存在key
的结果:
[
{
"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
答案 1 :(得分:0)
这里的解决方案不依赖于感兴趣的对象在数组中具有固定位置的假设:
.arr
| map( .[] | objects | .text )
| index("FooBar")
更强大:
.arr
| map( first(.[] | objects) // null | .text )
| index("FooBar")