0

Below function is giving me required result except the numbers (0,1,2,0) populating before JSON object beginning. Can someone help me to get rid of those numbers.

$V1='11' $V2='1881' $V3='111','222','333'

$body=CreateJsonBody $V1 $V2 $V3

function CreateJsonBody{

    param($objectId,$AttributeId,$AttributeValues)

    $jsonBase=@{"objectId"= $objectId;}
    $vlist = New-Object System.Collections.ArrayList
    $alist = New-Object System.Collections.ArrayList

    foreach ($Val in $AttributeValues) {
        $vlist.Add(@{"value"= $Val;})
    }

    $alist.Add(@{"AttributeId"= $AttributeId;"AttributeValues"=$vlist;})
    $jsonBase.Add("attributes",$alist)
    return $jsonBase | ConvertTo-Json -Depth 10
}

Output:

PS C:\WINDOWS\system32> $body

0

1

2

0

{
    "objectId":  "105",
    "attributes":  [
                       {
                           "AttributeId":  "1887",
                           "AttributeValues":  [
                                                  {
                                                      "value":  "111"
                                                   },
                                                   {
                                                      "value":  "222"
                                                   },
                                                   {
                                                      "value":  "333"
                                                   }
                                               ]
                       }
                   ]
}
stackprotector
  • 10,498
  • 4
  • 35
  • 64
  • The arraylist.Add method returns the index of the added object which is being manifested in your output. Set the ouput of those lines to either pipe to Out-Null or assign to $null. e.g. `$null = $vlist.Add(@{"value"= $Val;})` or `$vlist.Add(@{"value"= $Val;}) | Out-Null` – Daniel Sep 03 '21 at 06:32
  • `$Null = $vlist.Add(@{"value"= $Val;})`, see proposal: [`#15781` Strict Write-Output](https://github.com/PowerShell/PowerShell/issues/15781) – iRon Sep 03 '21 at 06:40
  • Does this answer your question? [Powershell ArrayList magically inserts a zero](https://stackoverflow.com/questions/52641400/powershell-arraylist-magically-inserts-a-zero) – iRon Sep 03 '21 at 06:41
  • Does this answer your question? [Correctly return array in powershell](https://stackoverflow.com/questions/61887780/correctly-return-array-in-powershell) – JosefZ Sep 04 '21 at 19:38

0 Answers0