The ConvertFrom-Json command is used to turn a JSON document into an object. For example:
'{ "Property": "Value" }' | ConvertFrom-Json
ConvertFrom-Json creates a PSCustomObject.
JSON understands a number of different data types, and each of these types is converted to an equivalent .NET type. The following example shows how each different type might be represented:
$object = @"
{ "Decimal": 1.23, "String": "string", "Int32": 1, "Int64": 2147483648, "Boolean": true } "@ | ConvertFrom-Json
Inspecting individual elements after conversion reflects the type, as demonstrated in the following example:
PS> $object.Int64.GetType() $object.Boolean.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Int64 System.ValueType True True Boolean System.ValueType
JSON serialization within PowerShell is useful, but it is not perfect. For example, consider the result of converting Get-Date:
PS> Get-Date | ConvertTo-Json
{ "value": "/Date(1489321529249)/", "DisplayHint": 2, "DateTime": "12 March 2017 12:25:29" }
The value includes a DisplayHintNoteProperty and a DateTimeScriptProperty, added to the DateTime object. These add an extra layer of properties when converting back from JSON:
PS> Get-Date | ConvertTo-Json | ConvertFrom-Json valueDisplayHintDateTime ----- ----------- -------- 12/03/2017 12:27:25 2 12 March 2017 12:27:25
The DateTime property can be removed using the following:
Get-TypeData System.DateTime | Remove-TypeData
DisplayHint is added by Get-Date, and therefore the command cannot be used in this context.
Any extraneous members such as this would have to be tested for invalid members prior to conversion, which makes the solution more of a problem:
PS> Get-TypeData System.DateTime | Remove-TypeData [DateTime]::Now | ConvertTo-Json | ConvertFrom-Json | Select-Object * Date : 12/03/2017 00:00:00 Day : 12 DayOfWeek : Sunday DayOfYear : 71 Hour : 12 Kind : Utc Millisecond : 58 Minute : 32 Month : 3 Second : 41 Ticks : 636249187610580000 TimeOfDay : 12:32:41.0580000 Year : 2017