Search code examples
jsonpowershellhashtablepscustomobject

How to init pscustomobjects array in pscustomobject


I try to make an object like this:

$bodyObject = [pscustomobject]@{
    'fields' = [pscustomobject]@{
        'fixVersions' = @([pscustomobject]@{
            'id' = $releaseId
        })
    }
};
$bodyJson = $bodyObject | ConvertTo-Json;
Write-Output $bodyJson;

I got the following output:

{
    "fields": {
        "fixVersions": [
            "@{id=16919}"
        ]
    }
}

How can I achieve valid JSON structure like this?

{
    "fields": {
        "fixVersions": [
            {"id": "16919"}
        ]
    }
}

Solution

  • When I just composed a question, the idea came to me. The problem was not in the way of creating my complex object, but in json serilizator. According to docs, default -Depth parameter value is 2. So, I changed the code like this

    $bodyObject = [pscustomobject]@{
        'fields' = [pscustomobject]@{
            'fixVersions' = @([pscustomobject]@{
                'id' = $releaseId
            })
        }
    };
    $bodyJson = $bodyObject | ConvertTo-Json -Depth 3; # HERE
    Write-Output $bodyJson;
    

    and got a correct JSON