我正在尝试使用jq命令展平JSON文件。但是输出重复了。
请在此处查看我的jqplay:https://jqplay.org/s/gwvMIH_fed
我的输入JSON:
{
"cost": 0.0,
"interval": "0:01:00",
"namespace": "Microsoft.ApiManagement/service",
"resourceregion": "australiaeast",
"timespan": "2019-05-22T00:00:00Z/2019-05-22T00:02:00Z",
"value": [
{
"id": "/my-api/providers/Microsoft.Insights/metrics/Capacity",
"name": {
"localizedValue": "Capacity",
"value": "Capacity"
},
"resourceGroup": "my-group",
"timeseries": [
{
"data": [
{
"average": 15,
"count": null,
"maximum": null,
"minimum": null,
"timeStamp": "2019-05-22T00:00:00+00:00",
"total": null
},
{
"average": 16,
"count": null,
"maximum": null,
"minimum": null,
"timeStamp": "2019-05-22T00:01:00+00:00",
"total": null
}
],
"metadatavalues": []
}
],
"type": "Microsoft.Insights/metrics",
"unit": "Percent"
}
]
}
我的预期输出:
{
"apiId": "/my-api/providers/Microsoft.Insights/metrics/Capacity",
"metrics": "Capacity",
"timestamp": "2019-05-22T00:00:00+00:00",
"value": 15
}
{
"apiId": "/my-api/providers/Microsoft.Insights/metrics/Capacity",
"metrics": "Capacity",
"timestamp": "2019-05-22T00:01:00+00:00",
"value": 16
}
任何人都可以看看提供的jqplay URL并提出建议。
答案 0 :(得分:1)
每个。[]就像一个“ for”循环,因此您观察到的乘法行为本质上是嵌套for循环的结果。似乎您想要的东西更接近:
.value[] as $v
| $v.timeseries[].data[] as $d
| {"apiId": $v.id,
"metrics": $v.name.value,
"timestamp": $d.timeStamp,
"value": $d.average }
使用JSON作为输入,这会生成两个JSON对象,尽管其中的第二个与您期望的输出结果稍有不同。
答案 1 :(得分:0)
使用基于步行路径的Unix实用程序 jtc
:
bash $ <input.json jtc -w'<id>l<A>v[-1][name][value]<M>v[-2]<average>l:<V>v[-1][timeStamp]' -T'{"apiId":{{A}},"metrics":{{M}},"value":{{V}},"timestamps":{{}}}'
{
"apiId": "/my-api/providers/Microsoft.Insights/metrics/Capacity",
"metrics": "Capacity",
"timestamps": "2019-05-22T00:00:00+00:00",
"value": 15
}
{
"apiId": "/my-api/providers/Microsoft.Insights/metrics/Capacity",
"metrics": "Capacity",
"timestamps": "2019-05-22T00:01:00+00:00",
"value": 16
}
bash $
walk-path there(-w
)仅将所有必需的JSON值收集到各自的命名空间(A
,M
,V
)中,以进行后续模板插值(注意最后一个步行元素不需要存储在名称空间中,因为可以使用{{}}
表示法对它进行插值)
PS>披露:我是jtc
-用于JSON操作的shell cli工具的创建者