在 jq 中增加 arg

Increment arg in jq

我有类似的东西:

jq --arg START 10 '[.z[] | select(has("name")) | {id: $START | tonumber, name}]'

转换为一个包含 'name' 键的对象数组,附加一个递增的 id,输出:

[
  {
    id: 10,
    name: "stuff"
  },
  {
    id: 10,
    name: "more stuff"
  }
]

如何递增 START arg 以使第二个对象的 ID 为 11 等等?

编辑:我应该发布原件 json:

{
  "u": "stuff",
  "x": [1,2,3],
  "y": {
    "field": "value"
  },
  "z": {
    "stuffWithoutName": {
       "ex": "stuff"
    },
    "zz": {
       "name": "change me",
       "more": "stuff"
    },
    "randomKey":  {
       "name": "change me",
       "random": "more stuff"
    }
  }
}

谢谢!

假设你的 jq 有 foreach:

# emit a stream of {id:_, value: _} objects
def counts(s; start):
  foreach s as $i (start-1; .+1; {id:., value: $i});

[ counts(.z[] | select(has("name")); $START|tonumber)
| {id, name: .value.name} ]

由于上面假设你有 foreach,你不妨也使用 --argjson 选项,它允许你将 START 的值作为 JSON 数字传递。

如果你的jq没有foreach,那么上面很容易修改为使用reduce代替。

后记

根据对问题的修改,您似乎希望您的 jq 程序具有以下形式:

.z = [ ... ]

.z |= [[.[] | select(has("name"))] | to_entries | ...

或同等学历。

您可以使用 to_entries,当给定一个数组时,它会给出每个项目的索引:

jq --arg START 10 '($START | tonumber) as $s
  | [.z[] | select(has("name"))]
  | to_entries
  | map({name:.value.name, id: ($s + .key) })'

这样,id10 + 0 变为 10 + n