我正在努力构建一个函数来构造API调用的json有效负载。json payload将有一个主“成员”,但我需要添加一个子成员,它实际上是一个json数组。我有这个 * 几乎 * 工作,但我一直无法让它 * 完全 * 工作。
以下是两个示例(产生不同但不正确的结果):
此示例生成了正确的结构(除了数组周围需要的开头和结尾{}:
[PSCustomObject] $contactMain = @{}
[PSCustomObject] $contactDetail_Native = @{}
[array] $contactDetail_Custom = @()
$contactDetail_Custom = `
[PSCustomObject]@{
field = '1'
value = '1001'
}
$contactDetail_Custom += $contactDetail_Custom
$contactDetail_Custom = `
[PSCustomObject]@{
field = '2'
value = '1002'
}
$contactDetail_Custom += $contactDetail_Custom
$contactDetail_Native = `
[ordered]@{
email = 'brucebanner@myfakeemail.com'
lastName = 'Banner'
firstName = 'Bruce'
}
$contactDetail_Native.Add('fieldValues', $contactDetail_Custom)
$contactMain | Add-Member -MemberType NoteProperty -Name 'contact' -Value $contactDetail_Native -Force
#$contactMain | Add-Member -MemberType NoteProperty -Name 'fieldValues' -Value $contactDetail_Custom -Force
$contactMain = $contactMain | ConvertTo-Json
$contactMain
本例呈现值,但fieldValues需要在联系人成员内:
[PSCustomObject] $contactMain = @{}
[PSCustomObject] $contactDetail_Native = @{}
[array] $contactDetail_Custom = @()
$contactDetail_Custom = `
[PSCustomObject]@{
field = '1'
value = '1001'
}
$contactDetail_Custom += $contactDetail_Custom
$contactDetail_Custom = `
[PSCustomObject]@{
field = '2'
value = '1002'
}
$contactDetail_Custom += $contactDetail_Custom
$contactDetail_Native = `
[ordered]@{
email = 'brucebanner@myfakeemail.com'
lastName = 'Banner'
firstName = 'Bruce'
}
#$contactDetail_Native.Add('fieldValues', $contactDetail_Custom)
$contactMain | Add-Member -MemberType NoteProperty -Name 'contact' -Value $contactDetail_Native -Force
$contactMain | Add-Member -MemberType NoteProperty -Name 'fieldValues' -Value $contactDetail_Custom -Force
$contactMain = $contactMain | ConvertTo-Json
$contactMain
我需要渲染的方式是这样的:
{"contact": {
"firstName": "Bruce",
"lastName": "Banner",
"email": "brucebanner@myfakeemail.com",
"fieldValues": [
{
"field": "1",
"value": "1001"
},
{
"field": "2",
"value": "1002"
}
]
}}
我做错了什么?
谢谢!
2条答案
按热度按时间gkn4icbw1#
您可能希望使用此
ConvertTo-Expression
来构建模板和/或获得PowerShell结构的印象:要自动构建
fieldValues
,你可以这样做:zmeyuzjn2#
看起来我自己就能搞清楚了。解决方案是使用我提供的第一个代码示例在ConvertTo-Jsoncmdlet上设置Depth参数。
下面是生成我需要的结果的最终版本: