我尝试使用jq将JSON输出转换为CSV。
这里的input.json(剥离了很多 - 我可能有多达600个数组元素,但每个数组元素相同):
{
"latitude": [39.582, 39.582, 39.582],
"longitude": [26.675, 26.675, 26.675],
"drivingDifficultyIndex": [0, 34, 34],
"iconCode": [31, 11, 11],
"observationTimeUtcIso": ["2016-06-26T00:20:00+0000", "2016-06-26T01:20:00+0000", "2016-06-26T02:20:00+0000"],
"precip1Hour": [0.0, 0.1, 0.5]
}
到目前为止,我最好的尝试是:
jq --raw-output 'keys , .[] | @csv'
使
"drivingDifficultyIndex","iconCode","latitude","longitude","observationTimeUtcIso","precip1Hour"
39.582,39.582,39.582
26.675,26.675,26.675
0,34,34
31,11,11
"2016-06-26T00:20:00+0000","2016-06-26T01:20:00+0000","2016-06-26T02:20:00+0000"
0,0.1,0.5
How to convert arbirtrary simple JSON to CSV using jq?提供了一些很好的提示,但我仍然以行(如上所述)而不是列结束数据。
我追求的是:
"latitude","longitude","drivingDifficultyIndex","iconCode","observationTimeUtcIso","precip1Hour"
39.582, 26.675, 0, 31, \2016-06-26T00:20:00+0000\", 0
39.582, 26.675, 34, 11, \"2016-06-26T01:20:00+0000\", 0.1
39.582, 26.675, 34, 11, \"2016-06-26T02:20:00+0000\", 0.5
每个阵列中最多有600个元素,我需要CSV文件为每个阵列分别设置一个列;第2行向下需要转置。
有人可以帮助jq产生我想要的输出吗?
...谢谢
更新:
jq --raw-output 'keys_unsorted, map(.[0]) , map(.[1]), map(.[2]) |@csv'
对于上面的示例3数组成员,给了我想要的东西。但是,我怎样才能解决更大(未知)的数组元素?
答案 0 :(得分:1)
事实上,使用transpose
可以提供一个简单的单行解决方案:
( keys_unsorted, ([.[]] | transpose)[]) | @csv
使用样本数据,使用-r选项调用jq会产生:
"latitude","longitude","drivingDifficultyIndex","iconCode","observationTimeUtcIso","precip1Hour"
39.582,26.675,0,31,"2016-06-26T00:20:00+0000",0
39.582,26.675,34,11,"2016-06-26T01:20:00+0000",0.1
39.582,26.675,34,11,"2016-06-26T02:20:00+0000",0.5