使用jq按特定键分组时修改数组元素

时间:2018-04-10 07:43:28

标签: json bash jq

是否可以在按特定键(.[].Parameter.Id)分组时修改/替换数组元素,以便此数组:

[{
    "Id": 48,
    "Parameter": {
        "Id": 17
    }
}, {
    "Id": 196,
    "Parameter": {
        "Id": 17
    }
}]

成为这个:

[
   {
    "p17": [48, 196]
   }
]

以下是完整示例的源JSON文件:

[{
    "Id": 78,
    "PromotionType": 2,
    "Amount": "100",
    "UpperLimit": null,
    "Variables": [{
        "Id": 100,
        "Parameter": {
            "Id": 30
        }
    }]
}, {
    "Id": 84,
    "PromotionType": 2,
    "Amount": null,
    "UpperLimit": null,
    "Variables": [{
        "Id": 48,
        "Parameter": {
            "Id": 17
        }
    }, {
        "Id": 196,
        "Parameter": {
            "Id": 17
        }
    }, {
        "Id": 59,
        "Parameter": {
            "Id": 21
        }
    }, {
        "Id": 60,
        "Parameter": {
            "Id": 21
        }
    }, {
        "Id": 62,
        "Parameter": {
            "Id": 21
        }
    }]
}, {
    "Id": 59,
    "PromotionType": 2,
    "Amount": "666.6",
    "UpperLimit": null,
    "Variables": [{
        "Id": 96,
        "Parameter": {
            "Id": 8
        }
    }, {
        "Id": 47,
        "Parameter": {
            "Id": 17
        }
    }]
}]

我想要实现的目标是:

[{
    "Id": 78,
    "PromotionType": 2,
    "Amount": "100",
    "UpperLimit": null,
    "Variables": [{
        "p30": [100]
    }]
}, {
    "Id": 84,
    "PromotionType": 2,
    "Amount": null,
    "UpperLimit": null,
    "Variables": [{
        "p17": [48, 196]
    }, {
        "p21": [59, 60, 62]
    }]
}, {
    "Id": 59,
    "PromotionType": 2,
    "Amount": "666.6",
    "UpperLimit": null,
    "Variables": [{
        "p8": [96]
    }, {
        "p17": [47]
    }]
}]

我正在阅读jq手册jq cookbook,并找到了一些可能有帮助但无法弄清楚如何制作的功能(例如with_entriesunique_byinputs)它有效。

对象/内部对象的数量也不固定。所以我不能简单地使用数组索引替换。

任何帮助都将不胜感激。

谢谢, 埃姆雷

1 个答案:

答案 0 :(得分:2)

jq 解决方案:

jq 'map(.Variables 
        |= (group_by(.Parameter.Id) 
            | map(("p" + (.[0].Parameter.Id | tostring)) as $pid 
                  | { ($pid) : map(.Id) }
              )
           )
    )' input.json

输出:

[
  {
    "Id": 78,
    "PromotionType": 2,
    "Amount": "100",
    "UpperLimit": null,
    "Variables": [
      {
        "p30": [
          100
        ]
      }
    ]
  },
  {
    "Id": 84,
    "PromotionType": 2,
    "Amount": null,
    "UpperLimit": null,
    "Variables": [
      {
        "p17": [
          48,
          196
        ]
      },
      {
        "p21": [
          59,
          60,
          62
        ]
      }
    ]
  },
  {
    "Id": 59,
    "PromotionType": 2,
    "Amount": "666.6",
    "UpperLimit": null,
    "Variables": [
      {
        "p8": [
          96
        ]
      },
      {
        "p17": [
          47
        ]
      }
    ]
  }
]