arrays - 使用带有内联输出的 jq 1.3 计算 JSON 数组的分组成员

标签 arrays json jq

我有一个 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"
]

能否请您建议如何生成所需的输出?

最佳答案

这是一种方法:

jq -r '.[]|.ASGname as $g|.instance_AZs|group_by(.)[]|"\($g).\(.[0]).\(length)"' file.json

关于arrays - 使用带有内联输出的 jq 1.3 计算 JSON 数组的分组成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55489052/

相关文章:

python 动态对象查询

java - 如何让我的 Setter 与我单独的类(class)进行交互?

json - 如何检查 JSON 是否包含在 golang 中的数组 JSON 对象中

bash - 如何将此 Bash 脚本转换为 PowerShell

json - 有没有办法使用 jq 通过其公共(public)键拆分 JSON 文件?

java - 是否可以将pdf文档保存到字节数组(java的aspose.pdf)

php - 从 mySQL 表中识别作业代码的更改

iteration - jq:迭代字符串中的正则表达式匹配

json - 在 bash 脚本中添加 JSON 元素

c# - 如何配置 WebMethods 以使用 DataContractJsonSerializer