我有一个JSON文件:
[
{
"instance_AZs": [
"us-east-1b",
"us-east-1b",
"us-east-1b",
"us-east-1c",
"us-east-1c",
"us-east-1a",
"us-east-1a",
"us-east-1c",
"us-east-1b",
"us-east-1a",
"us-east-1a",
"us-east-1c",
"us-east-1a",
"us-east-1b",
"us-east-1b",
"us-east-1c",
"us-east-1c",
"us-east-1b"
],
"ASGname": "myapp"
}
]
所需的输出是:
myapp.us-east-1a.5
myapp.us-east-1b.7
myapp.us-east-1c.6
据我所知,我可以使用jq 1.3语法编写以下代码:
cat file.json | jq -r '.[] | .ASGname, (.instance_AZs | group_by(.) | map(. | length , (. | unique ) [] ))'
哪个产生输出:
myapp
[
5,
"us-east-1a",
7,
"us-east-1b",
6,
"us-east-1c"
]
请问如何生成所需的输出?
答案 0 :(得分:2)
这是一种实现方法:
jq -r '.[]|.ASGname as $g|.instance_AZs|group_by(.)[]|"\($g).\(.[0]).\(length)"' file.json
答案 1 :(得分:2)
.[]
| .ASGname as $p
| reduce .instance_AZs[] as $k ({}; .[$k]+=1)
| keys_unsorted[] as $k
| "\($p).\($k).\(.[$k])"
将instance_AZs
减少到一个对象,在该对象中,唯一的数组元素是数组中重复计数的键,将其用于产生所需的输出。
或者,如果您坚持要这样做,则将组通过管道而不是map
插入插值字符串,即,请参阅@ hek2mgl的答案。