'Is it possible to include current time stamp in jq command?

I am running a curl rest-api call and try to extra some key/value pairs in UBUNTU. This is my current command:

curl ..... | jq -c '{"online": .switches.optional.online, "offline": .switches.optional.offline}'

and the output I've received is as this:

{ "online": 85, "offline": 196 }

But what I am really looking for is to have the current time-stamp included the json body, something as if:

   { "current-time": "Wed Apr 15 14:18:42 PDT 2020", "online": 85, "offline": 196 }

The API response body does not have the current timestamp message, can this be triggered by jq itself ?

Thanks.

Jack



Solution 1:[1]

It should be possible to pass the result of another command (or a variable etc) to the jq command.

If in bash, something like the following could work:

curl ..... | jq -c --arg datum "$(date)" '{"online": .switches.optional.online, "offline": .switches.optional.offline, "current-time": $datum}'

Here we pass the result of $(date) command into the jq filter, as the argument $datum.

The date command can give the current time formatted in many different ways.

Solution 2:[2]

jq has the now builtin:

TZ=UTC jq -n 'now | strftime("%a %b %d, %Y %Z %H:%M:%S")'
"Wed Apr 15, 2020 UTC 21:51:07"

Note that the environment variable TZ will affect the %Z portion of the string produced by strftime, but not the numerical time portion:

TZ=Australia/Sydney jq -n 'now | strftime("%a %b %d, %Y %Z %H:%M:%S")'
"Wed Apr 15, 2020 AEST 21:52:19"

By contrast, the strflocaltime function of both jq and gojq (the Go implementation of jq) will present the "local time" relative to TZ:

$ gojq -n 'now | strflocaltime("%a %b %d, %Y %Z %H:%M:%S")'
"Wed May 04, 2022 EDT 17:39:48"

$ TZ=Australia/Sydney gojq -n 'now | strflocaltime("%a %b %d, %Y %Z %H:%M:%S")'
"Thu May 05, 2022 AEST 07:40:00"

$ TZ=Australia/Sydney jq -n 'now | strflocaltime("%a %b %d, %Y %Z %H:%M:%S")'
"Thu May 05, 2022 AEST 07:40:00"

Solution 3:[3]

Assuming the curl response looks something like what I've hardcoded ...

$ jq --arg now "$(date)" '{"current-time": $now, "online": .switches.optional.online, "offline": .switches.optional.offline}' <<<'{ "switches": {"optional": {"online": 85, "offline": 196 }}}'

{
  "current-time": "Wed Apr 15 22:03:00 UTC 2020",
  "online": 85,
  "offline": 196
}

Try it online!

Hope this helps!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 O.O.
Solution 2
Solution 3 Bean Taxi