如何获得一个干净的数组作为输出

how to get a clean array as output

作为输入我有:

[
  {
    "backup": [
      {
        "timestamp": { "start": 1642144383, "stop": 1642144386 },
        "info": {  "size": 1200934840},
        "type": "full"
      },
      {
        "timestamp": {"start": 1642144388, "stop":  1642144392 },
        "info": { "size": 1168586300
        },
        "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 '.[]
   | [ .backup[] + {name} ]
   | max_by(.timestamp.stop)
'

(感谢@pmf)我可以重新订购这个

{
  "timestamp": {
    "start": 1642144388,
    "stop": 1642144392
  },
  "info": {
    "size": 1168586300
  },
  "type": "incr",
  "name": "dbname1"
}
{
  "timestamp": {
    "start": 1642144388,
    "stop": 1642144392
  },
  "info": {
    "size": 1168586300
  },
  "type": "incr",
  "name": "dbname2"
}

选择的是包含最大时间戳和添加到其中的名称的字典,是最后创建的数据库备份。可能有多个数据库。如何将输出形成为格式清晰的数组? 我希望

[
{
  "timestamp": {
    "start": 1642144388,
    "stop": 1642144392
  },
  "info": {
    "size": 1168586300
  },
  "type": "incr",
  "name": "dbname1"
},
{
  "timestamp": {
    "start": 1642144388,
    "stop": 1642144392
  },
  "info": {
    "size": 1168586300
  },
  "type": "incr",
  "name": "dbname2"
}
]

是的,我可以使用 sed 添加它,但我觉得 jq 应该能够做到这一点。那么问题来了,这个应该怎么写呢?

而不是 .[] | … 使用 map(…) 来保留数组。

jq 'map([.backup[] + {name}] | max_by(.timestamp.stop))'
[
  {
    "timestamp": {
      "start": 1642144388,
      "stop": 1642144392
    },
    "info": {
      "size": 1168586300
    },
    "type": "incr",
    "name": "dbname1"
  },
  {
    "timestamp": {
      "start": 1642144388,
      "stop": 1642144392
    },
    "info": {
      "size": 1168586300
    },
    "type": "incr",
    "name": "dbname2"
  }
]

Demo