I need to interact with an API that is expecting an array of objects, among other parameters. Example:
{
"fields": {
"somefield": "somevalue",
"someobject": {
"name": "foobar"
},
"versions": [
{
"name": "1.0"
}
]
}
}
With the help of this answer, I've tried two different ways of handling this. I've combined them into a single code example:
$versionName = New-Object -TypeName PSObject
$versionName | Add-Member -Name "name" -MemberType NoteProperty -Value "1.0"
$versionName2 = @{}
$versionName2.name = "1.0"
$postIssueBody = @{}
$postIssueBody.fields = @{}
$postIssueBody.fields.somefield = "somevalue"
$postIssueBody.fields.someobject = @{}
$postIssueBody.fields.someobject.name = "foobar"
$postIssueBody.fields.version = @($versionName)
$postIssueBody.fields.version2 = @()
$postIssueBody.fields.version2 += [pscustomobject]$versionName2
$postIssueRequestJson = $postIssueBody | ConvertTo-Json
$postIssueRequestJson
This results in the following output:
{
"fields": {
"somefield": "somevalue",
"someobject": {
"name": "foobar"
},
"version": [
"@{name=1.0}"
],
"version2": [
"@{name=1.0}"
]
}
}
As you can see, that's not going to fly as valid JSON. What is the best way to handle this assignment so that the version names are properly formed after going through ConvertTo-Json
?