使用jq删除JSON值中的重复项

时间:2015-11-17 20:50:13

标签: json jq

我有以下JSON:

[
  {
    "function": "ping",
    "name": "start",
    "servers": [
      {
        "load": 581.6875,
        "last_heard": 2.379324197769165,
        "version": "1.0",
        "hidden": false,
        "pid": "19735"
      },
      {
        "load": 444.0625,
        "last_heard": 1.3227169513702393,
        "version": "1.0",
        "hidden": false,
        "pid": "12092"
      }
    ]
  },
  {
    "function": "pong",
    "name": "middle",
    "servers": [
      {
        "load": 581.6875,
        "last_heard": 2.379324197769165,
        "version": "2.0",
        "hidden": false,
        "pid": "19735"
      },
      {
        "load": 444.0625,
        "last_heard": 1.3227169513702393,
        "version": "3.0",
        "hidden": false,
        "pid": "12092"
      },
      {
        "load": 444.0625,
        "last_heard": 1.3227169513702393,
        "version": "3.0",
        "hidden": false,
        "pid": "12093"
      }
    ]
  },
  {
    "function": "pang",
    "name": "end",
    "servers": [
      {
        "load": 581.6875,
        "last_heard": 2.379324197769165,
        "version": "2.0",
        "hidden": false,
        "pid": "19735"
      },
      {
        "load": 444.0625,
        "last_heard": 1.3227169513702393,
        "version": "2.0",
        "hidden": false,
        "pid": "12092"
      }
    ]
  }
]

(这只是一个样本,它是数百个条目)

我需要的是获得

[{"name": "start", "version": ["1.0"]},
{"name": "middle", "version": ["2.0", "3.0"]},
{"name": "end", "version": ["2.0"]}]

所以我需要删除无用的数据,然后获取一个名称列表及其“version”的唯一值。

我可以直到我有

{
  "name": "ping",
  "version": [
    "1.0",
    "1.0"
  ]
}
{
  "name": "pong",
  "version": [
    "2.0",
    "3.0",
    "3.0"
  ]
}
{
  "name": "pang",
  "version": [
    "2.0",
    "2.0"
  ]
}

使用

jq '.[] | {name: .function, version: [.servers[].version]}'

但我需要摆脱重复的价值观。 这可以使用jq吗?

2 个答案:

答案 0 :(得分:8)

你快到了。只需将version数组传递给unique函数:

jq '[.[]|{name, "version": [.servers[].version]|unique}]' input

答案 1 :(得分:0)

以下解决方案使用 reduce 在临时对象中收集版本密钥,并在最后使用

进行重复数据删除
 [
   . []
 | reduce .servers[].version as $v (
     {name, version:{}}
   ; .version[$v] = 1
   )
 | .version |= keys
 ]