带有值集合的Powershell ConvertTo-Json

时间:2018-08-27 23:00:15

标签: arrays json rest powershell collections

我正尝试使用Invoke-WebRequest cmdLet创建以下Json作为ReST请求的主体传递

{  
   "fields":{  
      "summary":"Execution Monday, August 27, 2018 3:24 PM",
      "project":{  
         "id":10401
      },
      "issuetype":{  
         "id":10103
      },
      "customfield_10527":[  
         "IC-54829",
         "IC-54830"
      ],
      "customfield_10539":[  
         "IC-54831"
      ]
   }
}

使用以下Powershell

Write-Output 'Creating Test Execution'
$dateString = Get-Date -Format f
$createTestExecutionBody = @{
    fields = @{
        summary = 'Execution ' + $dateString
        project = @{
            id = $projectId
        }
        issuetype = @{
            id = $testExecutionIssueTypeId
        }
        customfield_10527 = ConvertTo-Json -InputObject @($testsArray)
        customfield_10539 = ConvertTo-Json -InputObject @($testPlanKey) 
    }
}

这两个customfield属性是集合。这是我检查请求的HTTP时所看到的

{
    "fields":  {
                   "summary":  "Execution Monday, August 27, 2018 3:24 PM",
                   "customfield_10527":  "[\r\n    \"IC-54829\",\r\n    \"IC-54830\"\r\n]",
                   "customfield_10539":  "[\r\n    \"IC-54831\"\r\n]",
                   "project":  {
                                   "id":  "10401"
                               },
                   "issuetype":  {
                                     "id":  "10103"
                                 }
               }
}

如果我使用-Co​​mpress标志,则换行符会消失,但是我仍将集合括在引号中,并且将内部引号转义。这实际上是通过-Compress

在HTTP中作为主体传递的内容
{
    "fields":  {
                   "summary":  "Execution Monday, August 27, 2018 4:50 PM",
                   "customfield_10527":  "[\"IC-54829\",\"IC-54830\"]",
                   "customfield_10539":  "[\"IC-54831\"]",
                   "project":  {
                                   "id":  "10401"
                               },
                   "issuetype":  {
                                     "id":  "10103"
                                 }
               }
}

这两个customfields都是将包含一个或多个值的集合,它们在较早的步骤中作为数组构建。我需要帮助将其全部转换,尤其是将customfields转换为第一个json示例。

1 个答案:

答案 0 :(得分:0)

所以被问到,很快就回答了。我让事情变得更加艰难。这有效:

Write-Output 'Creating Test Execution'
$dateString = Get-Date -Format f
$createTestExecutionBody = @{
    fields = @{
        summary = 'Execution ' + $dateString
        project = @{
            id = $projectId
        }
        issuetype = @{
            id = $testExecutionIssueTypeId
        }
        customfield_10527 = @(
            $testsArray
        )
        customfield_10539 = @(
            $testPlanKey
        )
    }
}

我确信可能有更好的方法来完成此操作,因此我为快速的问与答表示歉意,但是如果知道powershell的人给出了正确的答案,我想把它留在这里。