使用 jq 同时遍历数组

Iterating over arrays simultaneously using jq

我正在描述我想要使用 jq

的输出

这是我的 json 文件

{
  "partitions": [
    {
      "replicas": [
        0,
        1,
        2
      ],
      "log_dirs": [
        "any",
        "any",
        "any"
      ]
    },
    {
      "replicas": [
        2,
        0,
        1
      ],
      "log_dirs": [
        "any",
        "any",
        "any"
      ]
    },
[...]

我想,对于 partitions[] 中的每个对象,将 log_dirs[] 中第 i 个字符串的值替换为它与 replicas[] 中第 i 个数字的连接,以便得到一些东西像这样

{
  "partitions": [
    {
      "replicas": [
        0,
        1,
        2
      ],
      "log_dirs": [
        "any0",
        "any1",
        "any2"
      ]
    },
    {
      "replicas": [
        2,
        0,
        1
      ],
      "log_dirs": [
        "any2",
        "any0",
        "any1"
      ]
    },
[...]

使用 reduce 循环和 range

.partitions[] |= reduce range(0; ( .replicas | length ) ) as $r 
  ( . ; .log_dirs[$r] += ( .replicas[$r] | tostring ) )

reduce 表达式通过遍历整个 log_dirs 数组直至 replicas 列表的长度并修改每个条目 .log_dirs[$r](此处 r 从 0 - replicas) 的长度,方法是在 replicas[$r] 处附加相应的值。由于replicas包含数字,需要将其转换为字符串进行追加操作。

jqplay - demo

我对此不太满意,但它确实有效:

jq '.partitions[] |= . + (
  . as $p | {
    log_dirs: [
      range(.replicas | length) |
      "\($p.log_dirs[.])\($p.replicas[.])"
    ]
  }
)' in.json