简体   繁体   中英

how to get a clean array as output

As input I have:

[
  {
    "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"
  }
]

using

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

(thanks @pmf) I can re-order this to

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

Selected is the dict containing the max timestamp and the name added to it, being the last created backup of a database. There are multiple databases possible. How can I form the output to a cleanly formatted array? I was hoping for

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

And yes, I can add this using sed but I feel jq should be able to do this. So the question is how can should this be written?

Instead of .[] | … .[] | … use map(…) to retain the array.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM