如何通过Json体传递变量Powershell



我想传递变量在这些值,但我不能让他们去,例如在user_id我想传递变量$userID这是我使用的Body的一个例子:

$body = '{
"data":
[
{
"user_id":$userID,
"type":"manual",
"date":"2021-01-30",
"duration":"150",
"jobcode_id":"15281216",
"notes":"This is a test of a manual time entry",
"customfields": {
"54138" : "IT Services",
"54136" : "Yes"
}
}
]
}'

我会使用双引号的Here-String:

$userID = 'Alex'
$body = @"
{
"data": [{
"user_id": "$userID",
"type": "manual",
"date": "2021-01-30",
"duration": "150",
"jobcode_id": "15281216",
"notes": "This is a test of a manual time entry",
"customfields": {
"54138": "IT Services",
"54136": "Yes"
}
}]
}
"@

$body现在包含:

{
"data": [{
"user_id": "Alex",
"type": "manual",
"date": "2021-01-30",
"duration": "150",
"jobcode_id": "15281216",
"notes": "This is a test of a manual time entry",
"customfields": {
"54138": "IT Services",
"54136": "Yes"
}
}]
}

$userID在您的示例中不替换它的值的原因是因为您正在使用单引号(')字符。PowerShell只在使用双引号(")字符时进行替换。

这会给你一个挑战,你的数据已经包含双引号。There Here字符串从Theo的答案工作得很好,但作为个人偏好,我会使用PowerShell哈希表来构建一个对象,并使用Convert-To-Json将其转换为Json。

的例子:

$userID = 'John'
$body = @{
"data" = ,@{
"user_id" = $userID;
"type" = "manual";
"date" = "2021-01-30";
"duration" = "150";
"jobcode_id" = "15281216";
"notes" = "This is a test of a manual time entry";
"customfield" = @{
"54138" = "IT Services";
"54136" = "Yes";
}   
}
}
$body | ConvertTo-Json -Depth 3
输出:

{
"data":  [
{
"notes":  "This is a test of a manual time entry",
"customfield":  {
"54138":  "IT Services",
"54136":  "Yes"
},
"duration":  "150",
"type":  "manual",
"date":  "2021-01-30",
"jobcode_id":  "15281216",
"user_id":  "John"
}
]
}

编辑:正如robdy在评论中提到的,应该使用Depth参数(我添加了它)。这里有一个很好的解释。

最新更新