我有一个API,它将组成员身份报告为一个数组,其中每个组都是一个包含成员数组的数组元素。我想简化数据,但不要删除数组边界。
如果有三个组API生成此输出,请将其命名为“3gr.json”:
[
{
"id" : "000E58D2E9B401400",
"members" : [
{
"id" : "000E58D2E9B401400",
"roomName" : "Room1",
"groupState" : {
"mute" : false,
"volume" : 15
},
"state" : {
"playbackState" : "STOPPED",
"volume" : 15,
"mute" : false
}
}
]
},
{
"id" : "000E58D2FA0601400",
"members" : [
{
"state" : {
"playbackState" : "STOPPED",
"volume" : 40,
"mute" : false
},
"id" : "000E58D2FA0601400",
"roomName" : "Room2",
"groupState" : {
"mute" : false,
"volume" : 40
}
}
]
},
{
"id" : "5CAAFD7B8C9801400",
"members" : [
{
"groupState" : {
"mute" : false,
"volume" : 15
},
"roomName" : "Room3",
"id" : "5CAAFD7B8C9801400",
"state" : {
"mute" : false,
"playbackState" : "STOPPED",
"volume" : 15
}
}
]
}
]
如果有一个组,API会产生此输出,请将其命名为“1gr.json”:
[
{
"id": "000E58D2E9B401400",
"members": [
{
"id": "000E58D2E9B401400",
"state": {
"volume": 44,
"mute": false,
"playbackState": "PAUSED_PLAYBACK",
"equalizer": {
"bass": 2,
"treble": 2,
"loudness": true
}
},
"roomName": "Room1",
"groupState": {
"volume": 46,
"mute": false
}
},
{
"id": "5CAAFDE9614001400",
"state": {
"volume": 54,
"mute": false,
"playbackState": "PAUSED_PLAYBACK",
"equalizer": {
"bass": 0,
"treble": 0,
"loudness": true
}
},
"roomName": "Room2",
"groupState": {
"volume": 65,
"mute": false
}
},
{
"id": "5CAAFD7B8C9801400",
"state": {
"volume": 41,
"mute": false,
"playbackState": "PAUSED_PLAYBACK",
"equalizer": {
"bass": 0,
"treble": 0,
"loudness": false
}
},
"roomName": "Room3",
"groupState": {
"volume": 41,
"mute": false
}
}
]
}
]
如果我使用jq
来处理此输出:
jq '.[].members[]|{name: .roomName, state: .state.playbackState, vol: .state.volume}' 3gr.json
我明白了:
{
"name": "Room1",
"state": "STOPPED",
"vol": 15
}
{
"name": "Room2",
"state": "STOPPED",
"vol": 40
}
{
"name": "Room3",
"state": "STOPPED",
"vol": 15
}
我得到了相同的输出结构(在这两个例子中,值并不重要),如果我处理'1gr.json':
{
"name": "Room1",
"state": "PAUSED_PLAYBACK",
"vol": 44
}
{
"name": "Room2",
"state": "PAUSED_PLAYBACK",
"vol": 54
}
{
"name": "Room3",
"state": "PAUSED_PLAYBACK",
"vol": 41
}
我想要的是保留组数组的数组边界。我尝试添加[ ]
的各种组合,但无济于事。所以我想看到的是:
[
[
{
"name": "Room1",
"state": "PAUSED_PLAYBACK",
"vol": 44
},
{
"name": "Room2",
"state": "PAUSED_PLAYBACK",
"vol": 54
},
{
"name": "Room3",
"state": "PAUSED_PLAYBACK",
"vol": 41
}
]
]
和
[
[
{
"name": "Room1",
"state": "PAUSED_PLAYBACK",
"vol": 44
}
],
[
{
"name": "Room2",
"state": "PAUSED_PLAYBACK",
"vol": 54
}
],
[
{
"name": "Room3",
"state": "PAUSED_PLAYBACK",
"vol": 41
}
]
]
答案 0 :(得分:1)
从本质上讲,您应该使用map
代替.[]
。
map(.members
| map({name: .roomName, state: .state.playbackState, vol: .state.volume}) )
(由于map(f)
只是[.[]|f]
,您也可以使用后一种形式,但写map
会使意图非常明确。)