jq replace part of value in json

Ryan Loeffler picture Ryan Loeffler · Mar 8, 2018 · Viewed 7.3k times · Source

I need to replace part of a value from a json output and i could easily do this using sed -i however it would also replace other parts of the file i dont want it to, unless im missing something. The out put 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 cant find anywhere else on the web that this has been accomplished.

Answer

RomanPerekhrest picture RomanPerekhrest · Mar 8, 2018

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"
}