使用jq从多维创建数组

时间:2016-10-11 12:57:14

标签: json hierarchical-data jq data-extraction

我想使用' 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": "*"
}
]

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

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

这是另一种解决方案:

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

答案 1 :(得分:0)

为便于阅读,此处列出的以下过滤器将按要求聚合输入:

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

如果你想避免在最后两行重复,你可以用以下代码替换最后四行:

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