Pass one of the elements as an array for JSON in powershell

Here is a small snippet of Powershell code:

$users = New-Object System.Collections.ArrayList
$userAsJson = '
{
    "name" : "abc",
    "companies" : ["facebook", "google"]
}'
$user = $userAsJson | ConvertFrom-Json
$null = $users.Add($user)
$users | ConvertTo-Json -Depth 5

It gives me the following expected result:

{
    "name":  "abc",
    "companies":  [
                      "facebook",
                      "google"
                  ]
}

Now I am dynamically trying to create a list of companies. I have tried all possible things that I can think of. Here is what I tried:

$company = New-Object System.Collections.ArrayList
$null = $company.Add('facebook')
$null = $company.Add('google')
$b = $company.ToArray()

$users = New-Object System.Collections.ArrayList
$userAsJson = '
{
    "name" : "abc",
    "companies" : $b
}'

$user = $userAsJson | ConvertFrom-Json
$null = $users.Add($user)

$users | ConvertTo-Json -Depth 5

Can someone suggest me what is the best way to achieve it?

+4
source share
1 answer

The PowerShell power is in the objects of the area until the time comes to interact with the outside world, for example, when writing to a file or creating a string representation of these objects.

In your case, this means:

# Array of companies; statically constructed here, but creating it
# dynamically works just as well.
$company = (
 'facebook',
 'google'
)

# Initialize the output collection.
# Note: Creating a [System.Collections.ArrayList] instance is
#       advisable for building up *large* arrays *incrementally*.
#       For smallish arrays, using regular PowerShell arrays will do; e.g.:
#         $users = @() # initialize array
#         $users += ... # append to array, but be aware that a *new* array 
#                         is created behind the scenes every time.
$users = New-Object System.Collections.ArrayList

# Add a user based on the $company array defined above as
# a [pscustomobject]
$null = $users.Add(
  [pscustomobject] @{
    name = 'abc'
    companies = $company
  }
)

# After all users have been added *as objects*, convert them to JSON.
$users | ConvertTo-Json -Depth 5

( , JSON):

{
  "name": "abc",
  "companies": [
    "facebook",
    "google"
  ]
}
+3

Source: https://habr.com/ru/post/1679933/


All Articles