powershell - 单值数组被转换为字符串 - Powershell
问题描述
我将其转换为 JSON 并发送 POST 请求,但值ContextTypes
不断转换为字符串。
$postParams = @{
instance=[PSCustomObject]@{
instanceId= $instanceId;
className="Permission";
schemaName="RBAC";
properties= @{
Name= $Name;
Description= $Description;
ServiceGPRId= 1;
CategoryId= 1;
ContextTypes=@('Object')
};
}
} | ConvertTo-Json
返回:
{
"instance": {
"instanceId": null,
"className": "Permission",
"schemaName": "RBAC",
"properties": {
"CategoryId": 1,
"ServiceGPRId": 1,
"Description": null,
"Name": null,
"ContextTypes": "Object"
}
}}
我已经看过其他答案并且也尝试 (@(...))
过,但它不起作用。出于某种原因,如果我在对象之外定义了相同的名称-值对properties
,它可以正常工作并返回:
{
"instance": {
"instanceId": null,
"className": "Permission",
"schemaName": "RBAC",
"ContextTypes": [
"Object"
],
"properties": {
"CategoryId": 1,
"ServiceGPRId": 1,
"Description": null,
"Name": null
}
}
}
我还尝试使用 -InputObject 方法将其转换为 Json,但结果相同。我如何确保ContextTypes
仍然是一个数组?
解决方案
您需要添加-Depth 3
到您的ConvertTo-Json
调用以确保您的对象图被序列化到其全部深度:
@{
instance= [PSCustomObject] @{
instanceId= $instanceId
className="Permission"
schemaName="RBAC"
properties= [PSCustomObject] @{
Name= $Name
Description= $Description
ServiceGPRId = 1
CategoryId = 1
ContextTypes = @('Object')
}
}
} | ConvertTo-Json -Depth 3
不幸的是,-Depth
默认为2
,这解释了你的 - 微妙 - 症状:本质上,你的数组被序列化为它的字符串扩展值,它只产生了它的(唯一的)元素(例如,"$(@('foo'))"
yield 'foo'
)。
有关背景信息,请参阅: