gpt4 book ai didi

json - jq - 将额外的 JSON 对象提取到新数组中

转载 作者:行者123 更新时间:2023-12-01 09:07:33 26 4
gpt4 key购买 nike

我有一些 JSON。它看起来像这样:

{
"Volumes": [
{
"Attachments": [
{
"VolumeId": "vol-11111111",
"State": "attached",
"DeleteOnTermination": false,
"Device": "/dev/sdz"
}
],
"Tags": [
{
"Value": "volume1",
"Key": "Name"
},
{
"Value": "00:00",
"Key": "Start"
},
{
"Value": "00:20",
"Key": "Finish"
},
{
"Value": "2",
"Key": "Period"
}
],
"VolumeId": "vol-11111111"
},
{
"Attachments": [
{
"VolumeId": "vol-22222222",
"State": "attached",
"DeleteOnTermination": false,
"Device": "/dev/sdz"
}
],
"Tags": [
{
"Value": "volume2",
"Key": "Name"
},
{
"Value": "00:00",
"Key": "Start"
},
{
"Value": "00:20",
"Key": "Finish"
},
{
"Value": "2",
"Key": "Period"
}
],
"VolumeId": "vol-22222222"
},
{
"Attachments": [
{
"VolumeId": "vol-333333333",
"State": "attached",
"DeleteOnTermination": false,
"Device": "/dev/sdz"
}
],
"Tags": [
{
"Value": "volume3",
"Key": "Name"
},
{
"Value": "00:00",
"Key": "Start"
},
{
"Value": "00:20",
"Key": "Finish"
},
{
"Value": "2",
"Key": "Period"
}
],
"VolumeId": "vol-33333333"
}
]
}

使用 jq,我能够提取以下信息:

VolumeId,Finish,Start,Period

使用 jq 命令

cat json | jq -r '[.Volumes[]|({VolumeId}+(.Tags|from_entries))|{VolumeId,Finish,Start,Period}]'

[
{
"VolumeId": "vol-11111111",
"Finish": "00:20",
"Start": "00:00",
"Period": "2"
},
{
"VolumeId": "vol-22222222",
"Finish": "00:20",
"Start": "00:00",
"Period": "2"
},
{
"VolumeId": "vol-33333333",
"Finish": "00:20",
"Start": "00:00",
"Period": "2"
}
]

一切正常。但是我需要额外提取.Attachments.Device。我正在寻找类似于以下内容的每个数组的输出:

 [
{
"VolumeId": "vol-11111111",
"Finish": "00:20",
"Start": "00:00",
"Period": "2",
"DeviceId": "/dev/sdz"
},
{
"VolumeId": "vol-22222222",
"Finish": "00:20",
"Start": "00:00",
"Period": "2",
"DeviceId": "/dev/sdz"
},
{
"VolumeId": "vol-33333333",
"Finish": "00:20",
"Start": "00:00",
"Period": "2",
"DeviceId": "/dev/sdz"
}
]

但是我无法弄清楚如何在不出错的情况下执行此操作。对我来说最合乎逻辑的方法是做类似的事情:

cat json | jq -r '[.Volumes[]|({VolumeId}+(.Attachments|from_entries)+(.Tags|from_entries))|{VolumeId,Finish,Start,Period,DeviceId}]'

但是我得到了错误:

jq: error (at <stdin>:91): Cannot use null (null) as object key

任何帮助找出我做错了什么以及如何解决它的帮助将不胜感激。

谢谢

最佳答案

最终,问题是您在 Attachments 数组上使用 from_entries 而它不起作用。 from_entries 采用一组键/值对对象来创建具有这些值的对象。但是,您没有键/值对,而是对象。如果您只是想组合它们,您应该使用 add

此外,没有名为 DeviceId 的属性,它是 Device。如果要选择 Device 属性并将其获取为 DeviceId,则需要提供正确的名称。

.Volumes | map(
({ VolumeId } + (.Attachments | add) + (.Tags | from_entries))
| { VolumeId, Finish, Start, Period, DeviceId: .Device }
)

关于json - jq - 将额外的 JSON 对象提取到新数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36393805/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com