如何压缩原始类型数组的输出?
How to compress output of arrays of primitive type?
我的 json 文件包含整数数组、字符串数组和对象。有没有一种方法可以压缩仅包含整数或字符串的数组的输出?
- 要么不显示这些数组的元素,要么
- 显示元素类型和数量
这是现在的样子:
$ jq "." foo.json
{
"version": [
"2.53.0",
"2.53.0",
"2.53.0",
"2.53.0",
"2.53.0",
"2.53.3",
"2.53.3",
"2.53.0",
"2.53.0",
"2.53.3",
"2.53.0",
"2.53.0",
"2.53.3",
"2.53.0",
"2.53.0",
"2.53.0",
"2.53.0",
"2.53.0",
"2.53.3",
"2.53.0"
],
"walltime_seconds": [
0.165,
0.199,
0.415,
0.193,
12.114,
0.227,
12.341,
12.145,
0.135,
0.326,
0.293,
0.19,
0.271,
0.103,
0.196,
0.18,
0.177,
0.166,
0.506,
0.568
]
}
这就是我想要的:
{
"version": "[..]",
"walltime_seconds": "[..]",
}
或这个
{
"version": "Array(str, 20)",
"walltime_seconds": "Array(float, 20)",
}
当然,压缩应该发生在 json 树中的任何地方,并且应该只对 int、str、float 而不是对象进行压缩。
这样做就可以了:
def compress:
if type == "array"
then (if all(.[]; type == "string") then "[string]"
elif all(.[]; type == "number") then "[number]"
elif all(.[]; type == "boolean") then "[boolean]"
else .
end)
else .
end;
walk(compress)
根据您的示例输入,结果将是:
{
"version": "[string]",
"walltime_seconds": "[number]"
}
包括null
的长度和句柄数组:
def compress:
def check($t):
if all(.[]; type == $t) then "[\($t)[\(length)]]" else empty end;
if type == "array"
then check("string") // check("number") // check("boolean") // check("null") // .
else .
end;
我的 json 文件包含整数数组、字符串数组和对象。有没有一种方法可以压缩仅包含整数或字符串的数组的输出?
- 要么不显示这些数组的元素,要么
- 显示元素类型和数量
这是现在的样子:
$ jq "." foo.json
{
"version": [
"2.53.0",
"2.53.0",
"2.53.0",
"2.53.0",
"2.53.0",
"2.53.3",
"2.53.3",
"2.53.0",
"2.53.0",
"2.53.3",
"2.53.0",
"2.53.0",
"2.53.3",
"2.53.0",
"2.53.0",
"2.53.0",
"2.53.0",
"2.53.0",
"2.53.3",
"2.53.0"
],
"walltime_seconds": [
0.165,
0.199,
0.415,
0.193,
12.114,
0.227,
12.341,
12.145,
0.135,
0.326,
0.293,
0.19,
0.271,
0.103,
0.196,
0.18,
0.177,
0.166,
0.506,
0.568
]
}
这就是我想要的:
{
"version": "[..]",
"walltime_seconds": "[..]",
}
或这个
{
"version": "Array(str, 20)",
"walltime_seconds": "Array(float, 20)",
}
当然,压缩应该发生在 json 树中的任何地方,并且应该只对 int、str、float 而不是对象进行压缩。
这样做就可以了:
def compress:
if type == "array"
then (if all(.[]; type == "string") then "[string]"
elif all(.[]; type == "number") then "[number]"
elif all(.[]; type == "boolean") then "[boolean]"
else .
end)
else .
end;
walk(compress)
根据您的示例输入,结果将是:
{
"version": "[string]",
"walltime_seconds": "[number]"
}
包括null
的长度和句柄数组:
def compress:
def check($t):
if all(.[]; type == $t) then "[\($t)[\(length)]]" else empty end;
if type == "array"
then check("string") // check("number") // check("boolean") // check("null") // .
else .
end;