I am working to built a function to construct a json payload for an API call. The json payload will have a main "member", but I need to add a sub-member which is really a json array. I have this almost working, but I have been unable to get it completely working.
Here are two examples (which produce different -but incorrect- results):
This example produces the correct structure (except for the required opening and closing {} around the array:
[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
This example renders the values, but fieldValues needs to be inside the contacts member:
[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
The way I need it to render is like this:
{"contact": {
"firstName": "Bruce",
"lastName": "Banner",
"email": "brucebanner@myfakeemail.com",
"fieldValues": [
{
"field": "1",
"value": "1001"
},
{
"field": "2",
"value": "1002"
}
]
}}
What am I doing wrong?
Thanks!