如何在 pscustomobject 中初始化 pscustomobjects 数组

How to init pscustomobjects array in pscustomobject

我尝试制作这样的对象:

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

我得到以下输出:

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

如何实现有效的 JSON 结构?

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

当我刚刚做一道题时,我想到了这个主意。 问题不在于创建复杂对象的方式,而在于 json serilizator。 根据文档,默认的 -Depth 参数值为 2。所以,我更改了这样的代码

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

并得到正确的 JSON