Home > Net >  Combine 3 jq commands into one command to yield a comma-delimited file
Combine 3 jq commands into one command to yield a comma-delimited file

Time:06-10

I have the following jq commands I want to run for each JSON object in an array that I'm processing:

jq -r '.[].Messages | .[].MessageId' combinded.json
jq -r '.[].Messages | .[].Attributes.SentTimestamp|tonumber|(. /1000) | strftime("%Y-%m-%dT%H:%M:%S %Z")' combinded.json
jq -r '.[].Messages | .[].Body | fromjson | .fileLocation.key' combinded.json

The output should appear as: MessageId, date-time, filelocation-key

I tried the usual things and nothing worked. Any suggestions?

This is sample JSON:

[
  {
    "Messages": [
      {
        "MessageId": "3ee11508-b7d0-4116-aed4-8c4abe399fd4",
        "Body": "{\"key\":\"tmp/20220607_015010_163546.pgp\",\"eTag\":\"506f370e6a184b38ae4ad9988e396384\",\"versionId\":null}",
        "Attributes": {
          "SentTimestamp": "1654581487500"
        }
      }
    ]
  },
  {
    "Messages": [
      {
        "MessageId": "3ee11508-b7d0-4116-aed4-8c4abe399fd7",
        "Body": "{\"key\":\"tmp/20220607_015010_163547.pgp\",\"eTag\":\"506f370e6a184b38ae4ad9988e396384\",\"versionId\":null}",
        "Attributes": {
          "SentTimestamp": "1654581487700"
        }
      }
    ]
  }
]

CodePudding user response:

Create an array with those 3 filters, then pass it on to join(", ")
(or @csv if you don't need those spaces)

.[].Messages[] | [ .MessageId,  (.Attributes.SentTimestamp | tonumber / 1000 | strftime("%Y-%m-%dT%H:%M:%S %Z")), (.Body | fromjson | .eTag) ] | join(", ")

Gives (with --raw output):

3ee11508-b7d0-4116-aed4-8c4abe399fd4, 2022-06-07T05:58:07 UTC, 506f370e6a184b38ae4ad9988e396384
3ee11508-b7d0-4116-aed4-8c4abe399fd7, 2022-06-07T05:58:07 UTC, 506f370e6a184b38ae4ad9988e396384

(The last filter had a missing key, so I've picked another for the example)

Online demo

  • Related