首页 > 解决方案 > Azure pipelines -Add new element in json array VSTS pipelines (Appsettings.json)

问题描述

Is this possible to add a new element in an array of appsetting.json in Azure Release Pipeline?

In appsetting.json I have array variable which I need to fill with another element during deployment through Azure Pipeline.

  "Array": [
                {
                    "Name": "AD1",
                    "IsDefault": "true",
                    "IdPEntityId": "URL1",
                    "Metadata": "XMLpath1"
                },
                {
                    "Name": "AD2",
                    "IsDefault": "false",
                    "IdPEntityId": "URL2",
                    "Metadata": "XMLPath2"
                }
]

Here in the above JSON array I need to add another one elemental last position (array-Index:2).

标签: jsontfsazure-devopsazure-pipelinesazure-pipelines-release-pipeline

解决方案


[CmdletBinding()]

param(
    [string] $AdName,
    [bool]   $AdIsDefault,
    [string] $AdIdPEntityId, 
    [string] $AdMetadata,
    [string] $AppSettingFilePath  
)
clear-Host

Write-Host 'Updating appsettings.json...' -ForegroundColor Yellow

function Format-Json([Parameter(Mandatory, ValueFromPipeline)][String] $json) {
  $indent = 0;
  ($json -Split '\n' |
    % {
      if ($_ -match '[\}\]]') {
        # This line contains  ] or }, decrement the indentation level
        $indent--
      }
      $line = (' ' * $indent * 2) + $_.TrimStart().Replace(':  ', ': ')
      if ($_ -match '[\{\[]') {
        # This line contains [ or {, increment the indentation level
        $indent++
      }
      $line
  }) -Join "`n"
}

$JsonDataAdd=@"
{
                    "Name":"$AdName",
                    "IsDefault": "$AdIsDefault",
                    "IdPEntityId":"$AdIdPEntityId",
                    "Metadata": "$AdMetadata"
}
"@
Write-Host ' Active directory details :' -ForegroundColor Yellow

Write-Host `n  $JsonDataAdd -ForegroundColor Green

$jsonData = Get-Content "$AppSettingFilePath" | Out-String | ConvertFrom-Json -ErrorAction Stop


$jsonData.IdentitySettings.ExternalProviders.Saml2Providers += (ConvertFrom-Json $JsonDataAdd)


$jsonData | ConvertTo-Json -Depth 10 |  Format-Json | Set-Content "$AppSettingFilePath" -Encoding UTF8

Write-Host 'Successfully Updated -appSettings.json  !' -ForegroundColor Yellow

推荐阅读