jq:根据参数切片数组

Joh*_* S. 6 bash json casting command-line-arguments jq

我试图在 jq 中对数组进行切片,其中结束索引作为来自 shell (bash) 的参数传递:

end_index=7
cat obj.json | jq --arg eidx $end_index, '.arr[0:$eidx]'
Run Code Online (Sandbox Code Playgroud)

当索引被硬编码时,这会按预期工作

cat obj.json | jq '.arr[0:7]'
Run Code Online (Sandbox Code Playgroud)

但在顶部的示例中,我收到一条错误消息

jq: error (at <stdin>:0): Start and end indices of an array slice must be numbers
Run Code Online (Sandbox Code Playgroud)

我怀疑这可能与 jq 如何处理切片运算符中的变量替换有关[:],但我解决该问题的尝试(例如通过将变量名称括在大括号中.arr[0:${eidx}])都没有奏效。

pea*_*eak 9

  1. 您可以使用 将字符串转换为数字tonumber,如下所示:

jq --arg eidx 1 '.arr[0:($eidx|tonumber)]'
Run Code Online (Sandbox Code Playgroud)
  1. 如果您的 jq 足够新,您可以--argjson使用--arg

jq --argjson eidx 1 '.arr[0:$eidx]'
Run Code Online (Sandbox Code Playgroud)