Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq replace part of value in json

I need to replace part of a value from a json output. I could easily do this using sed -i however it would also replace other parts of the file I don't want it to, unless I'm missing something. The output is

{
  "LastModified": "2018-03-07T17:24:33.000Z",
  "Key": "pending/archive/f7ab1684-e94d-483e-ace1-560367c1196c_1000_s.json"
}

and I need to replace the dash "-" on the LastModified value to a slash, then remove some stuff too like the "T" and the ".000Z" So I can eventually convert that timestamp to epoch.

I tried using cat list | jq -r '.[] | select (.LastModified == "-") .LastModified = "/"' and |= operator but I can't find anywhere else on the web that this has been accomplished.

like image 739
Ryan Loeffler Avatar asked Mar 08 '18 20:03

Ryan Loeffler


2 Answers

If your platform supports it, you could use the date functions to parse out then reformat the date string.

.LastModified |= (sub("\\.000Z$"; "Z") | fromdateiso8601 | strftime("%Y/%m/%d %H:%M:%S"))

Otherwise, you could use the usual string manipulation techniques.

.LastModified |= "\(.[:10] | sub("-"; "/"; "g")) \(.[11:19])"

Both results in the results:

{
  "LastModified": "2018/03/07 17:24:33",
  "Key": "pending/archive/f7ab1684-e94d-483e-ace1-560367c1196c_1000_s.json"
}
like image 29
Jeff Mercado Avatar answered Oct 17 '22 23:10

Jeff Mercado


With jq's sub() and fromdate() functions:

jq '.LastModified |= (sub("\\.000Z";"Z") | fromdate)' input.json

The output:

{
  "LastModified": 1520443473,
  "Key": "pending/archive/f7ab1684-e94d-483e-ace1-560367c1196c_1000_s.json"
}
like image 107
RomanPerekhrest Avatar answered Oct 17 '22 22:10

RomanPerekhrest