14

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.

Wilfred Hughes
  • 29,846
  • 15
  • 139
  • 192
Ryan Loeffler
  • 143
  • 1
  • 1
  • 5

2 Answers2

20

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"
}
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
4

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"
}
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272