ConvertFrom-Json

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 into 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() 
PS> $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
 
value DisplayHint DateTime ----- ----------- -------- 12/03/2017 12:27:25 2 12 March 2017 12:27:25  

The DateTime property can be removed using the following code:

Get-TypeData System.DateTime | Remove-TypeData 
Dates without type data

Get-Date will appear to return nothing after running the previous command. The date is still present; this is an aesthetic problem only. Without the type data, PowerShell does not know how to display the date, which is ordinarily composed as follows:

$date = Get-Date
'{0} {1}' -f $date.ToLongDateString(), $date.ToLongTimeString()

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 
PS> [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  
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.53.5