ArrchanaMohan
ArrchanaMohan

Reputation: 2566

How to append current date and time into existing json file using jq

I have below format of json file

{
  "username":"achu",
  "password":"test1234"
}

I just want to add timestamp into the above payload and send it as request for some service.

AS per I know the below command will help us to get current stamp on linux:

date +"%r"

but not sure how can I append this into the above payload as like below:

Expected:

{
  "username":"achu",
  "password":"test1234",
  "date":"1:20:30 AM PST"
}

jq --version

1.5v

Is it possible to get it like this?

Upvotes: 4

Views: 7922

Answers (3)

oguz ismail
oguz ismail

Reputation: 50795

JQ has builtin functions for playing with dates, such as:

. + {date: (now | strflocaltime("%r"))}

Upvotes: 13

peak
peak

Reputation: 116880

One of many possibilities:

$ jq --arg date $(date +"%r") '. + {date: $date}'

p.s. The jq program could be written as:

. + {$date}

p.p.s. Rather than continually asking whether something is possible using jq, you might find it a better investment of your time to become more familiar with jq. A good reference is the official manual: https://stedolan.github.io/jq/manual/

Upvotes: 5

James Brown
James Brown

Reputation: 37424

With GNU awk and gawk-json extension:

$ gawk '
@load "json"
{
   lines=lines $0                      # pack multiline json to a single record
   if(json_fromJSON(lines,data)==1) {  # convert json to an array
       data["date"]=strftime("%r %Z")  # get the date to the array
       print json_toJSON(data,1)       # output json
   }
}' file.json

Output in my tz:

{"username":"achu","password":"test1234","date":"07:46:57 AM EEST"}

Upvotes: 2

Related Questions