使用 jq 从多维数组创建数组

Create array from multi-dimensional one with jq

我想使用 'jq' json 处理器将 json 结构转换为简单对象数组。

我的结构是这样的:

{"nsgs": [
    {
        "comments": "text1",
        "properties": {
            "securityRules": [
                {
                    "name": "1",
                    "properties": {
                        "protocol": "TCP",
                        "sourcePortRange": "*"
                    }
                },
                {
                    "name": "2",
                    "properties": {
                        "protocol": "UDP",
                        "sourcePortRange": "*"
                    }
                }
            ]
        }
    },
    {
        "comments": "text2",
        "properties": {
            "securityRules": [
                {
                    "name": "3",
                    "properties": {
                        "protocol": "TCP",
                        "sourcePortRange": "*"
                    }
                },
                {
                    "name": "4",
                    "properties": {
                        "protocol": "UDP",
                        "sourcePortRange": "*"
                    }
                }
            ]
        }
    }
]}

而我想要得到的是:

[
{ "comments": "text1",
  "name": "1",
  "protocol": "TCP",
  "sourcePortRange": "*"
},

{ "comments": "text1",
  "name": "2",
  "protocol": "UDP",
  "sourcePortRange": "*"
},

{ "comments": "text2",
  "name": "3",
  "protocol": "TCP",
  "sourcePortRange": "*"
},

{ "comments": "text2",
  "name": "4",
  "protocol": "UDP",
  "sourcePortRange": "*"
}
]

我尝试了很多方法,但没有任何帮助。

感谢任何帮助。

为了方便阅读而在此处列出的以下过滤器将按要求聚合输入:

.nsgs
| map(.comments as $comments
      | .properties.securityRules[]
      | {comments: $comments,
         name, 
         protocol: .properties.protocol,
         sourcePortRange: .properties.sourcePortRange } )

如果你想避免最后两行的重复,你可以将最后四行替换为:

      | {comments: $comments, name }
        + (.properties | {protocol, sourcePortRange} ) )

这是另一个解决方案:

.nsgs | map({comments} + (.properties.securityRules[] | {name}+.properties))