jq 实用程序 - 提取某些 json 块
jq utility - extract certain json blocks
我正在使用 jq
实用程序格式化 curl 命令的 json 输出。我无法找到通过 position.That 提取 json 块的方法是说我是否只想打印最后一个 json 块或随机的 json 块仅第 5 或第 6 或第 5 和第 6,是否有 jq
选项或实现此目标的方法?
JSON 数组看起来像这样
[
{
"field1": "value1",
"field2": "value2",
"field3": "value3"
},
{
"field1": "value1",
"field2": "value2",
"field3": "value3"
},
{
"field1": "value1",
"field2": "value2",
"field3": "value3"
},
{
"field1": "value1",
"field2": "value2",
"field3": "value3"
}
]
最后:last
第 5 名:.[4]
第六名:.[5]
第 5 和第 6(作为数组).[4:6]
第 5 和第 6(作为数组)[ .[4], .[5] ]
第 5 和第 6(作为流).[4:6][]
第 5 和第 6(作为流).[4], .[5]
最后:.[-1]
n-th,其中 $n 在命令行中指定(从 0 开始索引):
jq --argjson n $n '.[$n]'
$m-th 和 $n-th(基于 0 的索引):'.[$m, $n]'
选择的元素pseudo-randomly(假设bash或bash-likeshell并且数组不太长):
jq --argjson prn $RANDOM '
if length > 32767 then "Sorry - this algorithm is too simplistic." | error
else .[$prn % length]
end
'
在不假设 bash-like 环境的情况下做出 pseudo-random 选择的另一种方法:
jq '
if length > 1e6 then "Sorry - this algorithm is too simplistic." | error
else
(now|tostring|sub(".*[.]";"")|tonumber) as $n
| .[$n % length]
end'
我正在使用 jq
实用程序格式化 curl 命令的 json 输出。我无法找到通过 position.That 提取 json 块的方法是说我是否只想打印最后一个 json 块或随机的 json 块仅第 5 或第 6 或第 5 和第 6,是否有 jq
选项或实现此目标的方法?
JSON 数组看起来像这样
[
{
"field1": "value1",
"field2": "value2",
"field3": "value3"
},
{
"field1": "value1",
"field2": "value2",
"field3": "value3"
},
{
"field1": "value1",
"field2": "value2",
"field3": "value3"
},
{
"field1": "value1",
"field2": "value2",
"field3": "value3"
}
]
最后:last
第 5 名:.[4]
第六名:.[5]
第 5 和第 6(作为数组).[4:6]
第 5 和第 6(作为数组)[ .[4], .[5] ]
第 5 和第 6(作为流).[4:6][]
第 5 和第 6(作为流).[4], .[5]
最后:.[-1]
n-th,其中 $n 在命令行中指定(从 0 开始索引): jq --argjson n $n '.[$n]'
$m-th 和 $n-th(基于 0 的索引):'.[$m, $n]'
选择的元素pseudo-randomly(假设bash或bash-likeshell并且数组不太长):
jq --argjson prn $RANDOM '
if length > 32767 then "Sorry - this algorithm is too simplistic." | error
else .[$prn % length]
end
'
在不假设 bash-like 环境的情况下做出 pseudo-random 选择的另一种方法:
jq '
if length > 1e6 then "Sorry - this algorithm is too simplistic." | error
else
(now|tostring|sub(".*[.]";"")|tonumber) as $n
| .[$n % length]
end'