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"
                                                   }
                                               ]
                       }
                   ]
}
4
  • 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 Commented Sep 3, 2021 at 6:32
  • $Null = $vlist.Add(@{"value"= $Val;}), see proposal: #15781 Strict Write-Output Commented Sep 3, 2021 at 6:40
  • Does this answer your question? Powershell ArrayList magically inserts a zero Commented Sep 3, 2021 at 6:41
  • Does this answer your question? Correctly return array in powershell Commented Sep 4, 2021 at 19:38

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.