如何在jq中添加索引

问题描述 投票:0回答:4

我想使用 jq 映射我的输入

["a", "b"]

输出

[{name: "a", index: 0}, {name: "b", index: 1}]

我已经到达

0 as $i | def incr: $i = $i + 1; [.[] | {name:., index:incr}]'

输出:

[
  {
    "name": "a",
    "index": 1
  },
  {
    "name": "b",
    "index": 1
  }
]

但我错过了一些东西。

有什么想法吗?

jq
4个回答
22
投票

这比你想象的要容易。

to_entries | map({name:.value, index:.key})

to_entries
接受一个对象并返回一个键/值对数组。对于数组,它有效地生成索引/值对。您可以将这些对映射到您想要的项目。


2
投票

更“实际操作”的方法是使用

reduce

["a", "b"] | . as $in | reduce range(0;length) as $i ([]; . + [{"name": $in[$i], "index": $i}])


1
投票

还有一些方法。假设

input.json
包含您的数据

["a", "b"]

然后您将 jq 调用为

jq -M -c -f filter.jq input.json

然后将生成以下任意一个

filter.jq
过滤器

{"name":"a","index":0}
{"name":"b","index":1}

1) 使用 keysforeach

   foreach keys[] as $k (.;.;[$k,.[$k]])
 | {name:.[1], index:.[0]}

编辑:我现在意识到

foreach E as $X (.; .; R)
形式的过滤器几乎总是可以重写为
E as $X | R
所以上面真的只是

   keys[] as $k
 | [$k, .[$k]]
 | {name:.[1], index:.[0]}

可以简化为

   keys[] as $k
 | {name:.[$k], index:$k}

2) 使用 keystranspose

   [keys, .]
 | transpose[]
 | {name:.[1], index:.[0]}

3)使用函数

 def enumerate:
    def _enum(i):
      if   length<1
      then empty
      else [i, .[0]], (.[1:] | _enum(i+1))
      end
    ;
    _enum(0)
  ;

   enumerate
 | {name:.[1], index:.[0]}

0
投票

这也应该可以解决问题:

[range(length) as $i | .[$i] | {name: ., index: $i}]

jqplay这里.

© www.soinside.com 2019 - 2024. All rights reserved.