使用 jq 处理数组中的 JSON 个数组
Processing JSON of arrays in array with jq
环境:JQ 1.5,Windows 64 位。
我有以下 JSON:
{
"unique": 1924,
"coordinates": [
{
"time": "2015-01-25T00:00:01.683",
"xyz": [
{
"z": 4,
"y": 2,
"x": 1,
"id": 99
},
{
"z": 9,
"y": 9,
"x": 8,
"id": 100
},
{
"z": 9,
"y": 6,
"x": 10,
"id": 101
}
]
},
{
"time": "2015-01-25T00:00:02.790",
"xyz": [
{
"z": 0,
"y": 3,
"x": 7,
"id": 99
},
{
"z": 4,
"y": 6,
"x": 2,
"id": 100
},
{
"z": 2,
"y": 9,
"x": 51,
"id": 101
}
]
}
]
}
并想用 jq 将其转换成这种 CSV 格式:
unique,time,id,x,y,z
1924,"2015-01-25T00:00:01.683",99,1,2,4
1924,"2015-01-25T00:00:01.683",100,8,9,9
(以此类推)
我尝试了一些东西,例如:
jq -r '{unique: .unique, coordinates: .coordinates[].xyz[] | [.id, .x, .y, .z], time: .coordinates.[].time} | flatten | @csv'
这给了我我想要的 JSON,但每个 id、x、y 和 z 都相乘(即每个唯一行出现四次 - id、x、y、z 各出现一次)。
给数组赋一个数,如
jq -r '{unique: .unique, coordinates: .coordinates[0].xyz[] | [.id, .x, .y, .z], time: .coordinates.[0].time} | flatten | @csv'
给了我 coordinates
数组的第一个索引,但我自然想要所有索引。
第一步是将结果压平成行。
[{ unique } + (.coordinates[] | { time } + .xyz[])]
这将产生每行对象数组:
[
{
"unique": 1924,
"time": "2015-01-25T00:00:01.683",
"id": 99,
"x": 1,
"y": 2,
"z": 4
},
{
"unique": 1924,
"time": "2015-01-25T00:00:01.683",
"id": 100,
"x": 8,
"y": 9,
"z": 9
},
{
"unique": 1924,
"time": "2015-01-25T00:00:01.683",
"id": 101,
"x": 10,
"y": 6,
"z": 9
},
{
"unique": 1924,
"time": "2015-01-25T00:00:02.790",
"id": 99,
"x": 7,
"y": 3,
"z": 0
},
...
]
然后只需将其转换为 csv 行即可。
["unique","time","id","x","y","z"] as $fields | $fields, (.[] | [.[$fields[]]]) | @csv
环境:JQ 1.5,Windows 64 位。
我有以下 JSON:
{
"unique": 1924,
"coordinates": [
{
"time": "2015-01-25T00:00:01.683",
"xyz": [
{
"z": 4,
"y": 2,
"x": 1,
"id": 99
},
{
"z": 9,
"y": 9,
"x": 8,
"id": 100
},
{
"z": 9,
"y": 6,
"x": 10,
"id": 101
}
]
},
{
"time": "2015-01-25T00:00:02.790",
"xyz": [
{
"z": 0,
"y": 3,
"x": 7,
"id": 99
},
{
"z": 4,
"y": 6,
"x": 2,
"id": 100
},
{
"z": 2,
"y": 9,
"x": 51,
"id": 101
}
]
}
]
}
并想用 jq 将其转换成这种 CSV 格式:
unique,time,id,x,y,z
1924,"2015-01-25T00:00:01.683",99,1,2,4
1924,"2015-01-25T00:00:01.683",100,8,9,9
(以此类推)
我尝试了一些东西,例如:
jq -r '{unique: .unique, coordinates: .coordinates[].xyz[] | [.id, .x, .y, .z], time: .coordinates.[].time} | flatten | @csv'
这给了我我想要的 JSON,但每个 id、x、y 和 z 都相乘(即每个唯一行出现四次 - id、x、y、z 各出现一次)。
给数组赋一个数,如
jq -r '{unique: .unique, coordinates: .coordinates[0].xyz[] | [.id, .x, .y, .z], time: .coordinates.[0].time} | flatten | @csv'
给了我 coordinates
数组的第一个索引,但我自然想要所有索引。
第一步是将结果压平成行。
[{ unique } + (.coordinates[] | { time } + .xyz[])]
这将产生每行对象数组:
[
{
"unique": 1924,
"time": "2015-01-25T00:00:01.683",
"id": 99,
"x": 1,
"y": 2,
"z": 4
},
{
"unique": 1924,
"time": "2015-01-25T00:00:01.683",
"id": 100,
"x": 8,
"y": 9,
"z": 9
},
{
"unique": 1924,
"time": "2015-01-25T00:00:01.683",
"id": 101,
"x": 10,
"y": 6,
"z": 9
},
{
"unique": 1924,
"time": "2015-01-25T00:00:02.790",
"id": 99,
"x": 7,
"y": 3,
"z": 0
},
...
]
然后只需将其转换为 csv 行即可。
["unique","time","id","x","y","z"] as $fields | $fields, (.[] | [.[$fields[]]]) | @csv