Here is a small Powershell code snippet:
$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 output:
{
"name": "abc",
"companies": [
"facebook",
"google"
]
}
Now, I'm dynamically trying to create the companies list. I tried all possible things which I can think of. Here is what I have 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 anyone suggest me what is the best way to achieve it?
$user = @{name='abc'}; $user.companies = 'facebook', 'google'; $user | convertto-json- why are you trying to embedd the arraylist into a string then convert it from the string back into powershell? What's that for?