如何通过 Json body Powershell 传递变量

How do I pass variables through a Json body 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 仅在您使用双引号 (") 字符时进行替换。

这会给您带来挑战,因为您的数据已经包含双引号。 Thehere Here string from Theo's answers 工作得很好,但作为个人偏好,我会使用 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.