我一直试图将一个相当平坦的json重新安排到更深入的结构中,到目前为止没有任何成功。这是我的源数据:
[ {
"id": "27",
"time": "2017-12-21 07:24:00",
"service_name": "prices",
"version": "61f4u8e",
"event": "Success"
},
{
"id": "28",
"time": "2017-12-21 07:23:00",
"service_name": "prices",
"version": "21c2f7d",
"event": "Fail"
},
{
"id": "29",
"time": "2017-12-21 07:21:00",
"service_name": "cart",
"version": "9ff24c4",
"event": "Success"
}
]
结果应如下所示:
[
{
"name": "cart",
"data": [
{
"date": "2017-12-21 07:21:00",
"details": {
"event": "Success",
"version": "9ff24c4"
}
}
]
},
{
"name": "prices",
"data": [
{
"date": "2017-12-21 07:24:00",
"details": {
"event": "Success",
"version": "61f4u8e"
}
},
{
"date": "2017-12-21 07:23:00",
"details": {
"event": "Fail",
"version": "21c2f7d"
}
}
]
}
]
所以,基本上按service_name分组并稍微移动其他字段。
到目前为止,我已成功分组,但只有一个级别:
group_by(.service_name) | map({name: .[0].service_name, data: .})
如果输入将始终具有上述示例中的所有字段,我该如何改变其他值?
答案 0 :(得分:1)
jq
解决方案:
jq '[group_by(.service_name)[]
| .[0].service_name as $name
| { name: $name,
data: map({ date: .time,
details: {event, version}})
}]' jsonfile
输出:
[
{
"name": "cart",
"data": [
{
"date": "2017-12-21 07:21:00",
"details": {
"event": "Success",
"version": "9ff24c4"
}
}
]
},
{
"name": "prices",
"data": [
{
"date": "2017-12-21 07:24:00",
"details": {
"event": "Success",
"version": "61f4u8e"
}
},
{
"date": "2017-12-21 07:23:00",
"details": {
"event": "Fail",
"version": "21c2f7d"
}
}
]
}
]