Let’s say I have a PSObject
with an integer and a date that I want to serialize to JSON and have recipients be able to deserialize it. In JavaScript to do this I get the following JSON:
JSON.stringify({Date: new Date(), Number: 23})
"{"Date":"2014-09-10T14:11:27.092Z","Number":23}"
JSON.parse(JSON.stringify({Date: new Date(), Number: 23}))
>> Object {Date: "2014-09-10T14:13:28.950Z", Number: 23}
That looks like pretty standard JSON that can be interpreted correctly by JavaScript.
However, it appears that PowerShell's ConvertTo-Json
is so inconsistent with DateTime
serialization that it can't even convert itself back and forth correctly. To fully illustrate this:
PS C:\dev> $testObj = New-Object -TypeName PSobject -Property @{ Date = Get-Date; Number = 23; }
PS C:\dev> $testObj
Number Date
------ ----
23 9/10/2014 9:52:14 AM
PS C:\dev\git\strawman> $testObj | ConvertTo-Json
{
"Number": 23,
"Date": {
"value": "\/Date(1410357134361)\/",
"DisplayHint": 2,
"DateTime": "Wednesday, September 10, 2014 9:52:14 AM"
}
}
PS C:\dev> $testObj | ConvertTo-Json | ConvertFrom-Json
Number Date
------ ----
23 @{value=9/10/2014 1:52:14 PM; DisplayHint=2; DateTime=Wednesday, September 10, 2014 9:52:14 AM}
Not only is the JSON it produces for the date property not valid at all and can't be interpreted correctly by JavaScript, but PowerShell's ConvertFrom-Json
can't even interpret it correctly to give it the same looking object back.
Is there any way to correctly serialize a PSObject
with a DateTime
to valid JSON content that can be correctly deserialized by recipients?