1

I have the following ps/json:

$a = '[{"Type":"1","Name":"A"},{"Type":"2","Name":"B"}]'
$ps = $a | ConvertFrom-Json
Type Name
---- ----
1    A
2    B

#Now, I want to add this array into another array, so the resulting json should look like this:
[[{"Type":"1","Name":"A"},{"Type":"2","Name":"B"}]]

Remove-TypeData System.Array #needed for workaround for powershell bug: https://stackoverflow.com/questions/20848507/why-does-powershell-give-different-result-in-one-liner-than-two-liner-when-conve/38212718#38212718

$w = @()
$w += , $ps
$w |ConvertTo-Json
[
    {
        "Type":  "1",
        "Name":  "A"
    },
    {
        "Type":  "2",
        "Name":  "B"
    }
]


#It's apparent that the $ps object was NOT added to an empty array as desired, however when multiple instances are added ($w += , $ps twice for example) it works as expected:

[
    [
        {
            "Type":  "1",
            "Name":  "A"
        },
        {
            "Type":  "2",
            "Name":  "B"
        }
    ],
    [
        {
            "Type":  "1",
            "Name":  "A"
        },
        {
            "Type":  "2",
            "Name":  "B"
        }
    ]
]

So it seems the array is there however the outer brackets are not being returned (as they should be)

I've read through other questions and could not find a resolution for this, if anyone is able to share?

Papi Abi
  • 173
  • 1
  • 10

1 Answers1

1

To avoid confusion, it's best to avoid the pipeline in this case (in which arrays are invariably enumerated):

$ps = '[{"Type":"1","Name":"A"},{"Type":"2","Name":"B"}]' | ConvertFrom-Json

# Wrap $ps in a single-element array.
$w = , $ps

# Workaround for Windows PowerShell:
# See https://stackoverflow.com/a/38212718/45375
Remove-TypeData -ErrorAction Ignore System.Array

# Pass the wrapper array via -InputObject to prevent enumeration.
ConvertTo-Json -InputObject $w -Compress

The above yields:

[[{"Type":"1","Name":"A"},{"Type":"2","Name":"B"}]]
mklement0
  • 382,024
  • 64
  • 607
  • 775