3

I have question regarding shell scripting and jq tool to create a json file with timestamps.

echo "{\"vtg\":[$value]}" | jq -a '. + {date: now|strflocaltime("%r")}' > sample.json 

With this command I am getting below json file.

{
 "vtg": [
 11.769,
 11.769,
 11.339,
 11.788,
 11.867,
 11.886,
 11.808,
 11.339,
 11.554,
 11.182
 ],
 "date": "03:31:52 PM"
}

But I want time stamp like,

"date": [
  15,
  31,
  52
]

When do

 strptime("%H:%M:%SZ")

I am supposed to get that time-stamp in the format I want. But it gives me error:

jq: error (at <stdin>:10): strptime/1 requires string inputs and arguments

Can someone help me how to get that time stamp in JSON file?

4

The strptime() function is used to parse a formatted time (the inverse of what strftime() does). You want strftime().

Using jq:

jq -n 'now as $t | { date: [ ($t|strftime("%H")), ($t|strftime("%M")), ($t|strftime("%S")) ] }'

This uses strftime() to format the time given by the now function. Use strflocaltime() to convert the time to local time.

If that's too wordy or seems inefficient (we're actually calling strftime() once for each element of the date array!), then consider creating a HH:MM:SS timestamp string, and then splitting it on the colons:

jq -n '{ date: (now | strftime("%H:%M:%S") | split(":")) }'

Either of the above commands may produce

{
  "date": [
    "07",
    "01",
    "23"
  ]
}

Complete script (uses jo to safely create the initial vtg array from the values of a named bash array):

#!/bin/bash

value=(11.769 11.769 11.339 11.788 11.867 11.886 11.808 11.339 11.554 11.182)

jo vtg="$( jo -a "${value[@]}" )" |
jq '. += now as $t | { date: [ ($t|strftime("%H")), ($t|strftime("%M")), ($t|strftime("%S")) ] }'

# or...

jo vtg="$( jo -a "${value[@]}" )" |
jq '. += { date: (now | strftime("%H:%M:%S") | split(":")) }'

You could obviously also create the date section of the data on the fly with jo reading from the date command:

jo vtg="$(  jo -a "${value[@]}" )" \
   date="$( jo -a $( date +'%H %M %S' ) )"

This relies on the shell splitting the output from date on the spaces in the format string. You will get the local time from the above.

The jo tool is available from https://jpmens.net/2016/03/05/a-shell-command-to-create-json-jo/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.