在 powershell 中将成员之一作为数组传递给 JSON

Pass one of the member as array for JSON in powershell

这是一个小的 Powershell 代码片段:

$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

它给了我以下预期输出:

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

现在,我正在尝试动态创建公司列表。我尝试了所有我能想到的可能的事情。这是我尝试过的:

$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

谁能建议我实现它的最佳方法是什么?

PowerShell 的强项在于停留在领域对象,直到与外界接口,比如写的时候到文件或创建这些对象的字符串表示。

在您的情况下,这意味着:

# 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 array 将是输出):

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