jq group by和Increment同时 [英] jq group by and Increment at same time

查看:143
本文介绍了jq group by和Increment同时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例 input1.json


[{
    "organizationId": "org1",
    "status": "UP",
    "server": "server1",
    "somekey1" : "somevalue1"
}, 
{
    "organizationId": "org1",
    "status": "DOWN",
    "server": "server2",
    "somekey2" : "somevalue2"
},
{
    "organizationId": "org1",
    "status": "DOWN",
    "server": "server3"
},
{
    "organizationId": "org2",
    "server": "server1",
    "status": "UP",
    "somekey2" : "somevalue2"
},
{
    "organizationId": "org2",
    "server": "server2",
    "status": "UP",
    "somekey4" : "somevalue4"
}]

预期 output.json


[{
        "organizationId": "org1",
        "server1": "UP",
        "server2": "DOWN",
        "server3": "DOWN",
        "Down_Count": 2,
        "somekey2" : "somevalue2"
    },
    {
        "organizationId": "org2",
        "server1": "UP",
        "server2": "UP",
        "Down_Count": 0,
       "somekey2" : "somevalue2"
    }]

输入是两个文件的数组对象.我的目标是

The input is an array object of two files. My objective is

  1. 通过按organizationId分组来增加并填充新字段Down_Count.我可以有多个具有相同organizationId的记录.因此,应根据状态DOWN将计数增加该次数.
  2. 合并serverstatus字段.例如,"server":"server1", "status":"down"应该直接作为server1:down出现在最终输出中.我可以使用jq '.[] |= . + {(.server):.status}'
  3. 独立尝试
  4. 并非所有对象中都提供所有键.因此,我应该能够将所需的键添加到最终输出中.假设我知道我要添加的密钥名称.在最终输出中,我仅添加了"somekey2" : "somevalue2"
  1. to increment and populate the new field Down_Count by grouping by organizationId. I can have multiple records with same organizationId. Hence, the count should be incremented that number of times subject to status DOWN.
  2. Merge server and status fields. For example "server":"server1", "status":"down" should come as server1:down directly in final output. I can try this one independently using jq '.[] |= . + {(.server):.status}'
  3. all the keys are not available in all the objects. Hence, I should be able to add the keys I want to the final output. Lets assume I know the key name I want to add. In the final output, I have added only "somekey2" : "somevalue2"

我发现使用jq cmd线路处理器将所有这些实现在一起时会遇到一些困难.有什么建议吗?

I'm finding some difficulties to achieve all these together using jq cmd line processor. Any suggestions please?

推荐答案

jq 解决方案:

jq solution:

jq 'group_by(.organizationId) 
    | map(reduce .[] as $o ({"Down_Count" : 0};
              if $o["status"] == "DOWN" then .Down_Count += 1 else . end
              | . + { ($o["server"]) : $o["status"],
                          "organizationId" : $o["organizationId"] }
          ))' input.json

输出:

[
  {
    "Down_Count": 2,
    "server1": "UP",
    "organizationId": "org1",
    "server2": "DOWN",
    "server3": "DOWN"
  },
  {
    "Down_Count": 0,
    "server1": "UP",
    "organizationId": "org2",
    "server2": "UP"
  }
]

这篇关于jq group by和Increment同时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆