解析 JSON 时出错:无效的 JSON 原语

问题描述 投票:0回答:1

我的 Azure YAML 管道在 Powershell 步骤失败,不知道为什么,但无论如何 ConvertFrom-Json 行都会失败

下面是 appsettings.json 文件,如下所示:

{
  "TestExecution": {
    "TestEnvironment": "$(RUNENVIRONMENTGLOBALLY)",
    "DefaultWaitInSec": 30
  }
}

下面是我正在使用的 YAML

variables:
  RUNENVIRONMENTGLOBALLY : PREPROD

 steps:
  - task: PowerShell@2
    displayName: 'Set Environment To Run'
    inputs:
      targetType: 'inline'
      script: |        
        $appsettingsPath = '$(Build.SourcesDirectory)\appsettings.json'
        $appsettingsContent = Get-Content -Path $appsettingsPath -Raw
        Write-Output $appsettingsContent

        try 
        {
            $appsettingsObject = ConvertFrom-Json $appsettingsContent
            Write-Output $appsettingsObject        
            $appsettingsObject.TestEnvironment = ${RUNENVIRONMENTGLOBALLY}
            $updatedAppsettings = ConvertTo-Json $appsettingsObject -Compress
            Set-Content -Path $appsettingsPath -Value $updatedAppsettings -Force
            Write-Output "Successfully updated appsettings.json"
        }
        catch
        {
              Write-Output "Error parsing JSON: $_"
        }
powershell azure-devops yaml devops azure-pipelines-yaml
1个回答
0
投票

请注意,引用管道变量的正确语法是

$(myvar)
,而不是
${myvar}

此外,json 字符串还有一个未被引用的额外属性 (

TestExecution
)

代替:

$appsettingsObject.TestEnvironment = ${RUNENVIRONMENTGLOBALLY}

尝试:

$appsettingsObject.TestExecution.TestEnvironment = "$(RUNENVIRONMENTGLOBALLY)"
© www.soinside.com 2019 - 2024. All rights reserved.