【问题标题】:How to init pscustomobjects array in pscustomobject [duplicate]如何在 pscustomobject 中初始化 pscustomobjects 数组
【发布时间】:2021-06-19 13:14:47
【问题描述】:

我尝试制作这样的对象:

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

我得到以下输出:

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

我怎样才能实现这样的有效 JSON 结构?

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

【问题讨论】:

  • ConvertTo-Json -> ConvertTo-Json -Depth 3(如果您有深度嵌套的对象,您可能希望将其设置为更高的数字)
  • 这是真的!谢谢,我刚看完MSDN就自己写了类似的答案

标签: json powershell hashtable pscustomobject


【解决方案1】:

当我刚刚提出一个问题时,我突然想到了这个想法。 问题不在于创建我的复杂对象,而在于 json 序列化器。 根据文档,默认 -Depth 参数值为 2。所以,我改变了这样的代码

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

得到了正确的 JSON

【讨论】:

    猜你喜欢
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 2019-09-29
    • 2011-09-08
    • 1970-01-01
    相关资源
    最近更新 更多