gpt4 book ai didi

json - jq:根据参数切片数组

转载 作者:行者123 更新时间:2023-11-29 09:50:56 26 4
gpt4 key购买 nike

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

end_index=7
cat obj.json | jq --arg eidx $end_index, '.arr[0:$eidx]'

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

cat obj.json | jq '.arr[0:7]'

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

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

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

最佳答案

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

jq --arg eidx 1 '.arr[0:($eidx|tonumber)]'
  1. 如果您的 jq 足够新,您可以使用 --argjson 而不是 --arg:

jq --argjson eidx 1 '.arr[0:$eidx]'

关于json - jq:根据参数切片数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44995626/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com