Home > database >  Need help updating time element with output from jq?
Need help updating time element with output from jq?

Time:02-10

Current object with proposed format

[
  {
    "time": "2022-01-28T17:50:31.620Z"
  }
]

Command executed to convert from iso8601 to unix

jq '.[].time | sub("\.[0-9] Z$"; "Z") | fromdate' time_test.json

Output 1643392231

I've tried varying combinations but how to do I update the time value in the object. I can get the conversion to work but can't seem to update the value with the output.

Expected Result -

[
  {
    "time": "1643392231"
  }
]

CodePudding user response:

You mapped all the values in the array but you're not actually modifying or recreating the array.

To modify, use an assignment: (you were almost there)

.[].time |= (sub("\\.\\d Z$"; "Z") | fromdate)

To recreate, map it.

map(.time |= (sub("\\.\\d Z$"; "Z") | fromdate))

CodePudding user response:

Cancel the fractional seconds and you're good to go with fromdate. To escape within the regex, use double backslashes.

jq 'map(.time |= (sub("\\.\\d "; "") | fromdate))'
[
  {
    "time": 1643392231
  }
]

Demo

  • Related