I want to create a JSON object in powershell, for sending messages to slack from a build pipeline. The JSON I will be creating looks like this :
{
"blocks":[
{
"type":"header",
"text":{
"type":"plain_text",
"text":"Release completed"
}
},
{
"type":"divider"
},
{
"type":"section",
"fields":[
{
"type":"mrkdwn",
"text":"*Release number*\nRelease-17"
},
{
"type":"mrkdwn",
"text":"*User*\nJohn.Smith"
},
{
"type":"mrkdwn",
"text":"*Source version*\n20230110.1"
}
]
}
]
}
So it has an array in there, and a few things that I am struggling with! So far, I am doing the following :
$jsonBase = @{}
$blocksList = New-Object System.Collections.ArrayList #this is the main 'blocks' array
$fieldsList = New-Object System.Collections.ArrayList #create a list for the 'fields' section
$fieldsList.Add(@{"type"="mrkdwn";"text"="*Release number*\nRelease-17";})
$fieldsList.Add(@{"type"="mrkdwn";"text"="*User*\nJohn.Smith";})
$fieldsList.Add(@{"type"="mrkdwn";"text"="*Source version*\n20230110.1";})
$textData = @{"type"="plain_text";"text"="Release completed";} #create an object for the header text
$dividerData = @{"type"="divider";} #create an object for the divider
$blocksList.Add(@{"type"="header"; "text"=$textData})
$blocksList.Add(@{"type"="divider"})
$blocksList.Add(@{"type"="section"; "fields"=$fieldsList;})
$jsonBase.Add("blocks",$blocksList)
write-output $jsonBase | ConvertTo-Json
But my outputted JSON is not correct at all!
{
"blocks": [
{
"text": "System.Collections.Hashtable",
"type": "header"
},
{
"type": "divider"
},
{
"fields": "System.Collections.Hashtable System.Collections.Hashtable System.Collections.Hashtable",
"type": "section"
}
]
}