How to stop Powershell 7 ConvertFrom-Json reformatting timestamps?

Viewed 303
Get-Content 'file.json' | ConvertFrom-Json

This produces a different result for powershell 5 vs 7.

v5 gives me actual timestamp values from the json: eg 2018-01-26T17:48:51.220Z
v7 gives me reprocessed timestamp values from the json  eg 26/01/2018 17:48:51

How can I get v7 to behave as v5? I need the original values from the json.

1 Answers

The behavior of ConvertFrom-Json changed in PowerShell [Core] v6+: string values formatted with the o (round-trip) standard date/time format are now converted to [datetime]) instances rather than being parsed as strings - this is a convenient way to round-trip timestamps via (v6+) ConvertTo-Json, without having to do explicit to/from string conversions.

If you need the old behavior back, convert the resulting [datetime] instances back to strings explicitly, using .ToString('o').

Here's a simple example:

# v6+
PS> ('{ "timestamp": "2018-01-26T17:48:51.220Z" }' | 
       ConvertFrom-Json).timestamp.ToString('o')

2018-01-26T17:48:51.2200000Z
  • There is some flexibility around variations in the input format: the fractional seconds are optional, and if, present, the number of decimal places is allowed to vary.

  • By contrast, the o format always uses 7 decimal places, which differs from your input.

    • You're free to apply custom formatting based on a fixed number of decimal places, but note that you won't be able to tell how many decimal places were actually used in the input.
      • E.g., to get 3 decimal places:
        [datetime]::UtcNow.ToString("yyyy-MM-dd'T'HH':'mm':'ss'.'fffK")
  • If you want to prevent the to-[datetime] conversion at the source, you'll have to use a lower-level approach - ConvertFrom-Json doesn't offer a solution.

Related