How to convert string to JSON with powershell

Scenario:

we have the next string:
AZURE_TOKEN_URL=https://login.microsoftonline.com/xxxxx-xxxx-xxxx/oauth2/v2.0/token MANAGER_API_CLIENT_ID=xxxxx-xxxxxx ENABLE_ORYX_BUILD=true SIM_REQUEST_LIMIT=2 CustomerValue2=v1.1.0

we want to have it format:

[
{
"name": "AZURE_TOKEN_URL",
"slotSetting": false,
"value": "https://login.microsoftonline.com/xxxxx-xxxx-xxxx/oauth2/v2.0/token"
},
{
"name": "MANAGER_API_CLIENT_ID",
"slotSetting": false,
"value": "xxxxx-xxxxxx"
},
{
"name": "ENABLE_ORYX_BUILD",
"slotSetting": false,
"value": "true"
},
{
"name": "SIM_REQUEST_LIMIT",
"slotSetting": false,
"value": "2"
},
{
"name": "CustomerValue2",
"slotSetting": false,
"value": "v1.1.0"
}
]

Why do we need such conversion:

When we need to pass multiple settings to Web App configuration part over command:

az webapp config appsettings set

Example of code:

$Webapp_setting = 'AZURE_TOKEN_URL=https://login.microsoftonline.com/xxxxx-xxxx-xxxx/oauth2/v2.0/token MANAGER_API_CLIENT_ID=xxxxx-xxxxxx ENABLE_ORYX_BUILD=true SIM_REQUEST_LIMIT=2 CustomerValue2=v1.1.0'

$WebAppNameParamsArray = $Webapp_setting -split ' '

$settings = @()
foreach ($pair in $WebAppNameParamsArray) {
$key, $value = $pair -split '=', 2
$setting = @{
name = $key
slotSetting = $false
value = $value
}
$settings += $setting
}
$jsonString = $settings | ConvertTo-Json -Depth 10
Write-Output $jsonString >> params3.json
az webapp config appsettings set --resource-group $resource_group --name $Webapp_name --settings "@params3.json"

About nicoljako

Cofounder Kresalo., sysadmin, architect of IT infrastructures, DevOps
This entry was posted in Azure DevOps and tagged , , , . Bookmark the permalink.

Leave a comment