如何通过 Json 主体 Powershell 传递变量

问题描述

我想为这些值传递变量,但我无法让它们进入例如 user_id 我想传递变量 $userID 这是我正在使用的 Body 示例:

__glibc_likely (__libc_multiple_threads == 0)

解决方法

我会为此使用双引号的 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","54136": "Yes"
        }
    }]
}
,

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

这会给您带来挑战,即您的数据已经包含双引号。 Theo 的答案中的 Here 字符串效果很好,但作为个人偏好,我会使用 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 参数(我已经添加了它)。可以在 here 中找到一个很好的解释。