gpt4 book ai didi

json - 如何使用 jq 获得每个组和子组的最大值

转载 作者:行者123 更新时间:2023-12-05 05:48:51 24 4
gpt4 key购买 nike

jq 是一个了不起的工具,它可以做很多事情。作为我的输入

[
{
"backup": [
{
"timestamp": { "start": 1642144383, "stop": 1642144386 },
"info": { "size": 1200934840},
"type": "full"
},
{
"timestamp": {"start": 1642144388, "stop": 1642144392 },
"info": { "size": 1168586300
},
"type": "incr"
},
{
"timestamp": {"start": 1642145388, "stop": 1642145392 },
"info": { "size": 1168586330
},
"type": "incr"
}
],
"name": "dbname1"
},
{
"backup": [
{
"timestamp": { "start": 1642144383, "stop": 1642144386 },
"info": { "size": 1200934840},
"type": "full"
},
{
"timestamp": {"start": 1642144388, "stop": 1642144392 },
"info": { "size": 1168586300
},
"type": "incr"
}
],
"name": "dbname2"
}
]

和使用

jq 'map([.backup[] + {name}] | max_by(.timestamp.stop))'

我获得了最新的 timestamp.stop 名称。我应该如何更改它以获得名称和组的最新 timestamp.stop?在 SQL 中,这类似于 max(.timestamp.stop) group by .name,.type希望输出如下:

[
{
"timestamp": {
"start": 1642144383,
"stop": 1642144386
},
"info": {
"size": 1200934840
},
"type": "full",
"name": "dbname1"
},
{
"timestamp": {
"start": 1642145388,
"stop": 1642145392
},
"info": {
"size": 1168586330
},
"type": "incr",
"name": "dbname1"
},
{
"timestamp": {
"start": 1642144383,
"stop": 1642144386
},
"info": {
"size": 1200934840
},
"type": "full",
"name": "dbname2"
},
{
"timestamp": {
"start": 1642144388,
"stop": 1642144392
},
"info": {
"size": 1168586300
},
"type": "incr",
"name": "dbname2"
}
]

最佳答案

移除内部括号以展平数组,然后 group_by 两个条件(这使您的条件成为一个数组),并 map 您的 max_by到结果数组:

jq 'map(.backup[] + {name}) | group_by([.name, .type]) | map(max_by(.timestamp.stop))'
[
{
"timestamp": {
"start": 1642144383,
"stop": 1642144386
},
"info": {
"size": 1200934840
},
"type": "full",
"name": "dbname1"
},
{
"timestamp": {
"start": 1642145388,
"stop": 1642145392
},
"info": {
"size": 1168586330
},
"type": "incr",
"name": "dbname1"
},
{
"timestamp": {
"start": 1642144383,
"stop": 1642144386
},
"info": {
"size": 1200934840
},
"type": "full",
"name": "dbname2"
},
{
"timestamp": {
"start": 1642144388,
"stop": 1642144392
},
"info": {
"size": 1168586300
},
"type": "incr",
"name": "dbname2"
}
]

Demo

关于json - 如何使用 jq 获得每个组和子组的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70752174/

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