Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell ConvertFrom-Json with arrays adds extra spaces to an array value

When writing a powershell script with a ConvertFrom-Json, it seems that values in arrays are converted with additional spaces when casting them to a string. The following code shows this in a small code sample:

$object = @"
     { 
          "object":
          {            
            "prop1": "value",
            "array":[
               { "key": "value"},
               { "key2": "valuevalue"},
               { "key3": "valuevalue"},
               { "key4": "valuevalue"},
               { "key5": "valuevalue"}
            ]
          }
     } 
"@ | ConvertFrom-Json

$object.object.prop1
$object.object.array.key

$t = $object.object.prop1
$t2= $object.object.array.key
"""$t"""
"""$t2"""

Output:

value
value
"value"
"value    "

Where are the extra spaces coming from in the last value? When adding more value pairs to the array, more spaces are added.

like image 653
Peter Avatar asked Mar 15 '16 15:03

Peter


1 Answers

It is not about ConvertFrom-Json, it is about $array.value. Starting from v3 or v4 PowerShell lets to get the specified property of array items using the dot notation. If a property is missing then the result is null unless the strict mode is on. In the latter case it fails.

Here is the example:

$array = @(
    [PSCustomObject]@{key = 'value'}
    [PSCustomObject]@{key2 = 'valuevalue'}
)

$result = $array.key
$result.GetType().Name
"[$result]"

Output (note the result type and the extra space)

Object[]
[value ]

So the result is an array. When you cast an array to string its items are joined with a space as the default separator (can be altered by $OFS).

If you run the above example in PowerShell v2 it gets [] because v2 does not supports getting array item properties using the dot notation.

If you run the example with Set-StrictMode -Version 2 then it fails with an error The property 'key' cannot be found on this object. It fails in all PowerShell versions. In v2 because the array does not have the property key. In a later version because the second array item does not have this property.

like image 87
Roman Kuzmin Avatar answered Oct 07 '22 23:10

Roman Kuzmin