如何在 Powershell 中扩展 JSON 字符串中的变量?

How do I expand variables in a JSON string in Powershell?

目标:从一个 API 请求中获取信息,将这些信息存储到变量中并传递到一个新的 API 请求中以发出 JIRA 问题。

环境:

问题:目标的前两步没有问题。但是我不确定如何正确构建最后一步。

$summary = 'summary'
$desc = 'desc'

$Body = '{
    "fields": {
       "project": {"key": "ABC"},
       "summary": "${summary}",
       "description": ${desc},
       "issuetype": {"name": "Story"},
       "assignee" : {"name":"bob"}
   }
}'

实际结果:变量按字面解释。

预期结果:应在字符串中扩展变量。

我尝试过的:

非常感谢。

您可以构建一个 PsObject 并使用 ConvertTo-Json 将其转换为 Json 格式。 像这样

$firstname = "myFirstName"
$lastname = "myLastName"
$properties = [ordered]@{
    firstname = $firstname
    lastname = $lastname
}
$obj = New-Object psobject -Property $properties; 
$body = convertto-json $obj


PS >$body

{
    "firstname":  "myFirstName",
    "lastname":  "myLastName"
    
}

有多种方法可以做到这一点,具体取决于 body json 需要多大,您可以选择使用

方法一,创建一个double-quotedHere-String(不需要转义其他double-quotes):

$summary = 'summary'
$desc    = 'desc'
$Body    = @"
{
    "fields": {
        "project": {"key": "ABC"},
        "summary": "$summary",
        "description": "$desc",
        "issuetype": {"name": "Story"},
        "assignee" : {"name":"bob"}
    }
}
"@

方法 2:使用 self-defined 占位符创建 body 作为模板,如果需要可多次使用

$summary  = 'summary'
$desc     = 'desc'
$template = @'
{
    "fields": {
        "project": {"key": "ABC"},
        "summary": "@@SUMMARY@@",
        "description": "@@DESCRIPTION@@",
        "issuetype": {"name": "Story"},
        "assignee" : {"name":"bob"}
    }
}
'@

$Body = $template -replace '@@SUMMARY@@', $summary -replace '@@DESCRIPTION@@', $desc

方法 3:创建编号占位符以与 -f 格式运算符一起使用。 这样做的缺点是 ALL other existing curly brackets { and } have to be double..

$summary  = 'summary'
$desc     = 'desc'
$template = @'
{{
    "fields": {{
        "project": {{"key": "ABC"}},
        "summary": "{0}",
        "description": "{1}",
        "issuetype": {{"name": "Story"}},
        "assignee" : {{"name":"bob"}}
    }}
}}
'@

$Body = $template -f $summary, $desc

方法 4,创建 body 作为嵌套的 PsCustomObject 并将其转换为 Json

$summary = 'summary'
$desc    = 'desc'
$Body = [PsCustomObject]@{
    fields = [PsCustomObject]@{
        project = [PsCustomObject]@{key = 'ABC'}
        summary = $summary
        description = $desc
        issuetype = [PsCustomObject]@{name = 'Story'}
        assignee = [PsCustomObject]@{name = 'bob'}
    }
} | ConvertTo-Json -Depth 3  # you can also set this way higher to be on the safe side