以下是一个小型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
有谁能告诉我实现它的最佳方法是什么?
答案 0 :(得分:3)
PowerShell的优势在于保留在领域对象中,直到与外部世界的接口,例如写入文件时 em>或创建这些对象的字符串表示。
在您的情况下,这意味着:
# 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"
]
}