json - 以值作为标头的 Json 到 CSV 转换
问题描述
我有一个下面的 JSON 文件,需要转换为 CSV 文件,其中一些值作为标题,下面的值应该被填充。下面是示例 json
{
"environments" : [ {
"dimensions" : [ {
"metrics" : [ {
"name" : "count",
"values" : [ "123" ]
}, {
"name" : "response_time",
"values" : [ "15.7" ]
}],
"name" : "abcd"
}, {
"metrics" : [ {
"name" : "count",
"values" : [ "456" ]
}, {
"name" : "response_time",
"values" : [ "18.7" ]
}],
"name" : "xyzz"
}
这是我已经尝试过的
jq -r '.environments[].dimensions[] | .name as $p_name | .metrics[] | .name as $val_name | if $val_name == "response_time" then ($p_name,$val_name, .values[])' input.json
预计为
name,count,response_time
abcd, 123, 15.7
xyzz, 456, 18.7
解决方案
如果目标是依靠 JSON 本身以“metrics”数组呈现它们的任何顺序提供标头名称,那么请考虑:
.environments[].dimensions
| ["name", (.[0] | .metrics[] | .name)], # first emit the headers
( .[] | [.name, (.metrics[].values[0])] ) # ... and then the data rows
| @csv
推荐阅读
- javascript - 三.js雾不渲染?
- xml - Anypoint CloudHub Deploy 无法更新应用程序
- mockito - 等到@KafkaListener 用@EmbeddedKafka 完成测试中的消息处理
- javascript - 通过 css 和 ::focus 嵌套选择
- android - how to get timestamp of notification on android onNotificationPosted()
- php - 如何在 Ubuntu 14.04 上安装/启用 PHP 7.0 zip 扩展?
- flutter - 没有为类定义方法“TweenAnimationBuilder”
- excel - 计算列中的时间差并将其保存为具有多个电子表格的许多 excel 文件,PYTHON
- angular - 订阅可观察者不会执行
- javascript - 在 php 中使用 LocalStorage 变量