要在嵌套数组中添加的键值

时间:2019-10-27 12:03:08

标签: json jq

这是我尝试使用jq解析的json

{
    "orgs": {
        "org1": [{
                "space": "landscape2",
                "tag": "landscape2",
                "manager": {
                    "destination": "destination1"
                }},
            {
                "space": "landscape3",
                "tag": "landscape3",
                "manager": {
                    "destination1": "approuter",
                    "destination2": "approuter2"
                }},
            {
                "space": "landscape4",
                "app": "",
                "l_port_increment": 25,
                "host": "",
                "port": ""
            }],
        "org2": [
        {
                "space": "landscape1",
                "app": "ain-hana-chisel-cs",
                "l_port_increment": 13,
                "host": "10.03.76.234",
                "port": "30044"
            },
            {
                "space": "landscape3",
                "tag": "landscape3",                
                "manager1": {
                    "destination5": "service-v2",
                    "destination6": "service-v2"
                },
                "manager": {
                    "destination": "destination1"
                },
                "l_port_increment": 25,
                "host": "",
                "port": ""
            }   ]       }    }

我正在寻找以下输出,其中tag应该是过滤器之一。

{
  "orgs: "org1",
  "space": "landscape3",
  "tag": "landscape3",
  "manager": {
    "destination1": "approuter",
    "destination2": "approuter2"
  }
}
{
  "orgs": "org2",
  "space": "landscape3",
  "tag": "landscape3",
  "manager1": {
    "destination5": "service-v2",
    "destination6": "service-v2"
  },
  "manager": {
    "destination": "destination1"
  },
  "l_port_increment": 25,
  "host": "",
  "port": ""
}

使用此代码,我可以部分实现结果,但是无法获取组织的详细信息。     .orgs [] | 。[] | select(。“ tag” ==“ landscape3”)|选择(。“经理”)

我的实际输出如下。如何使用jq做到这一点?我尝试了几种方法,但无法获得所需的输出

 {
  "space": "landscape3",
  "tag": "landscape3",
  "manager": {
    "destination1": "approuter",
    "destination2": "approuter2"
  }
}
{
  "space": "landscape3",
  "tag": "landscape3",
  "manager1": {
    "destination5": "service-v2",
    "destination6": "service-v2"
  },
  "manager": {
    "destination": "destination1"
  },
  "l_port_increment": 25,
  "host": "",
  "port": ""
}

1 个答案:

答案 0 :(得分:0)

您对任务的描述不太清楚,但是我想您正在寻找类似的东西:

.orgs
| keys_unsorted[] as $k
| {orgs:$k} + first(.[$k][] | select(has("manager") and .tag == "landscape3"))

对于orgs中的每个键,从对应的数组中选择具有manager作为键和tag: landscape键-值对的对象,将orgs: <key>添加到第一个并输出结果对象。如果选择了多个对象,则除第一个对象外的其余对象将被忽略。