我有以下格式的JSON:
{
"@version": "2.7.0",
"site": {
"@name": "http://api:9999",
"@ssl": "false",
"alerts": [
{
"pluginid": "10094",
"desc": "<p>Base64 encoded data was disclosed by the application/web server<\/p>",
"instances": [
{
"uri": "http://api:9999",
"method": "POST",
"evidence": "DxyPP_YQ6qdWA_Kw_ZLgYilIkXCz93Xs1CeJPvg"
},
{
"uri": "http://api:9999",
"method": "POST",
"evidence": "eyJuYmYiOjE121lMWF1siSG9tZUFwcCJdfQ"
}
],
"count": "37"
}
]
}
}
我想展平内部数组-.site.alerts.instances
以获取以下JSON:
{
"@name": "http://api:9999",
"@ssl": "false",
"alerts": [
{
"pluginid": "10094",
"desc": "<p>Base64 encoded data was disclosed by the application/web server<\/p>",
"uri": "http://api:9999",
"method": "POST",
"evidence": "DxyPP_YQ6qdWA_Kw_ZLgYilIkXCz93Xs1CeJPvg",
"count": "37"
},
{
"pluginid": "10094",
"desc": "<p>Base64 encoded data was disclosed by the application/web server<\/p>",
"uri": "http://api:9999",
"method": "POST",
"evidence": "eyJuYmYiOjE121lMWF1siSG9tZUFwcCJdfQ",
"count": "37"
}
]
}
我能够通过使用以下JQ模式来展平内部JSON数组:
.site.alerts[] as $in | $in.instances[] as $h | $in | del(.instances) as $in2 | $h * $in2
这给了我非常接近的结果:
{
"uri": "http://api:9999",
"method": "POST",
"evidence": "DxyPP_YQ6qdWA_Kw_ZLgYilIkXCz93Xs1CeJPvg",
"pluginid": "10094",
"desc": "<p>Base64 encoded data was disclosed by the application/web server</p>",
"count": "37"
}
{
"uri": "http://api:9999",
"method": "POST",
"evidence": "eyJuYmYiOjE121lMWF1siSG9tZUFwcCJdfQ",
"pluginid": "10094",
"desc": "<p>Base64 encoded data was disclosed by the application/web server</p>",
"count": "37"
}
但不是完美的结果。这些对象不在数组中,并且不包含父对象中不属于数组一部分的字段(例如.site.@name
)。
您能帮我改善我创建的JQ模式吗?
谢谢!
答案 0 :(得分:3)
这是一个非常好的努力。您的想法是正确的,您已经确保.instances[]
数组是平坦的,只需根据需要使用该逻辑来重新构造JSON
jq '{ "@name" : .site."@name",
"@ssl" : .site."@ssl",
"alerts": [.site.alerts[] as $in | $in.instances[] as $h | $in | del(.instances) as $in2 | $h * $in2 ]}' json