0

我有一个这样的 JSON (sample.json):

{
  "sheet1": [
    {
      "hostname": "sv001",
      "role": "web",
      "ip1": "172.17.0.3"
    },
    {
      "hostname": "sv002",
      "role": "web",
      "ip1": "172.17.0.4"
    },
    {
      "hostname": "sv003",
      "role": "db",
      "ip1": "172.17.0.5",
      "ip2": "172.18.0.5"
    }
  ],
  "sheet2": [
    {
      "hostname": "sv004",
      "role": "web",
      "ip1": "172.17.0.6"
    },
    {
      "hostname": "sv005",
      "role": "db",
      "ip1": "172.17.0.7"
    },
    {
      "hostname": "vsv006",
      "role": "db",
      "ip1": "172.17.0.8"
    }
  ],
  "sheet3": []
}

我想提取这样的数据:

表 1

jq '(某事命令)' sample.json

{
    "web": {
        "hosts": [
            "172.17.0.3",
            "172.17.0.4"
        ]
    },
    "db": {
        "hosts": [
            "172.17.0.5"
        ]
    }
}

是否可以使用 jq map 进行重建?(我会将结果重用于 ansible 库存。)

4

2 回答 2

1

这是一个简短、直接且高效的解决方案——高效的部分原因是它group_by通过以下通用辅助函数避免了:

def add_by(f;g): reduce .[] as $x ({}; .[$x|f] += [$x|g]);
.sheet1
| add_by(.role; .ip1) 
| map_values( {hosts: .} )

输出

这会产生所需的输出:

{
 "web": {
    "hosts": [
      "172.17.0.3",
      "172.17.0.4"
    ]
  },
  "db": {
    "hosts": [
      "172.17.0.5"
    ]
  }
}
于 2019-09-21T20:18:44.050 回答
0

如果目标是按每个工作表中的角色重新组合 ip,您可以这样做:

map_values(
    reduce group_by(.role)[] as $g ({};
        .[$g[0].role].hosts = [$g[] | del(.hostname, .role)[]]
    )
)

这会产生这样的东西:

{
  "sheet1": {
    "db": {
      "hosts": [
        "172.17.0.5",
        "172.18.0.5"
      ]
    },
    "web": {
      "hosts": [
        "172.17.0.3",
        "172.17.0.4"
      ]
    }
  },
  "sheet2": {
    "db": {
      "hosts": [
        "172.17.0.7",
        "172.17.0.8"
      ]
    },
    "web": {
      "hosts": [
        "172.17.0.6"
      ]
    }
  },
  "sheet3": {}
}

https://jqplay.org/s/3VpRc5l4_m

如果您想将所有内容展平为仅保留唯一 ips 的单个对象,则可以使所有内容基本相同,您只需要在分组之前展平输入并删除map_values/1调用。

$ jq -n '
reduce ([inputs[][]] | group_by(.role)[]) as $g ({};
    .[$g[0].role].hosts = ([$g[] | del(.hostname, .role)[]] | unique)
)
'
{
  "db": {
    "hosts": [
      "172.17.0.5",
      "172.17.0.7",
      "172.17.0.8",
      "172.18.0.5"
    ]
  },
  "web": {
    "hosts": [
      "172.17.0.3",
      "172.17.0.4",
      "172.17.0.6"
    ]
  }
}

https://jqplay.org/s/ZGj1wC8hU3

于 2019-09-21T18:03:06.980 回答