[
{
"Description": "Copied for Destination xxx from Sourc 30c for Snapshot 1. Task created on X,52,87,14,76.",
"Encrypted": false,
"ID": "snap-074",
"Progress": "100%",
"Time": "2019-06-11T09:25:23.110Z",
"Owner": "883065",
"Status": "completed",
"Volume": "vol1",
"Size": 16
},
{
"Description": "Copied for Destination yy from Source 31c for Snapshot 2. Task created on X,52,87,14,76.",
"Encrypted": false,
"ID": "snap-096",
"Progress": "100%",
"Time": "2019-06-11T10:18:01.410Z",
"Owner": "1259",
"Status": "completed",
"Volume": "vol-2",
"Size": 4
}
]
我有要使用以下命令转换为csv的json文件:
jq -r '. | map(.Description[], .Encrypted, .ID, .Progress, .Time, .Owner, .Status, .Volume, .Size | join(",")) | join("\n")' snapshots1.json
但是我遇到了错误:
jq: error (at snapshots1.json:24): Cannot iterate over string ("Copied for...)
我在jq: error: Cannot iterate over string中看到过类似的帖子,但找不到错误。任何帮助表示赞赏。
答案 0 :(得分:0)
我认为您在正确的轨道上。这是我的处理方式:
jq -r '.[] | map(..) | @csv' snapshot1.json > snapshot1.csv
您的代码有几个小问题:
.Descriptions[]
-说明没有数组,因此方括号不起作用-没有要打开的数组。.[]
,然后从那里进行实验。编辑:拼写
答案 1 :(得分:0)
在此处使用..
来提取对象中的“值”存在风险:如果输入对象中键的顺序在对象之间不同怎么办?
这是解决此问题和其他问题的通用过滤器。它还发出合适的“标题”行:
def object2array(stream):
foreach stream as $x (null;
if . == null then $x | [true, keys_unsorted] else .[0]=false end;
(if .[0] then .[1] else empty end),
.[1] as $keys | $x | [getpath( $keys[] | [.]) ] );
def data: [{a:1,b:2}, {b:22,a:11,c:0}];
object2array(data[])
产生:
["a","b"]
[1,2]
[11,22]
正好用管道输送到@csv
或@tsv
。
因此,解决原始问题的方法基本上是:
object2array(.[]) | @csv
答案 2 :(得分:0)
jq -r '(map(keys) | add | unique) as $cols | map(. as $row | $cols | map($row[.])) as $rows | $cols, $rows[] | @csv' snapshots1.json >> myfile.csv
找到了这个post来解释此代码,它对我有用。