微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何通过 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 中找到一个很好的解释。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。