1

I am converting this to JSON and sending in a POST request but the value of ContextTypes keeps getting converted to string.

$postParams = @{
        instance=[PSCustomObject]@{
                instanceId= $instanceId;
                className="Permission";
                schemaName="RBAC";
                properties= @{
                        Name= $Name;
                        Description= $Description;
                        ServiceGPRId= 1;
                        CategoryId= 1;
                        ContextTypes=@('Object')
                };
         }
    } | ConvertTo-Json

returns:

{
"instance":  {
                 "instanceId":  null,
                 "className":  "Permission",
                 "schemaName":  "RBAC",
                 "properties":  {
                                    "CategoryId":  1,
                                    "ServiceGPRId":  1,
                                    "Description":  null,
                                    "Name":  null,
                                    "ContextTypes":  "Object"
                                }
}}

I have seen other answers and have tried (@(...)) as well, it doesn't work. For some reason, if I define the same name-value pair outside of the properties object, it works fine and returns:

{
"instance":  {
                 "instanceId":  null,
                 "className":  "Permission",
                 "schemaName":  "RBAC",
                 "ContextTypes":  [
                                      "Object"
                                  ],
                 "properties":  {
                                    "CategoryId":  1,
                                    "ServiceGPRId":  1,
                                    "Description":  null,
                                    "Name":  null
                                }                    
             }

}

I also tried converting it to Json using the -InputObject method, but that gives same results. How do I make sure ContextTypes remains an array?

izSaad
  • 579
  • 6
  • 25

1 Answers1

1

You need to add -Depth 3 to your ConvertTo-Json call to ensure that your object graph is serialized to its full depth:

@{
        instance= [PSCustomObject] @{
                instanceId= $instanceId
                className="Permission"
                schemaName="RBAC"
                properties= [PSCustomObject] @{
                        Name= $Name
                        Description= $Description
                        ServiceGPRId = 1
                        CategoryId = 1
                        ContextTypes = @('Object')
                }
         }
} | ConvertTo-Json -Depth 3

Unfortunately, -Depth defaults to 2, which explains your - subtle - symptom: essentially, your array was serialized as its string-expanded value, which yielded just its (only) element (e.g., "$(@('foo'))" yields 'foo').

For background information, see:

mklement0
  • 382,024
  • 64
  • 607
  • 775