PowerShell Hashtable to JSON 不带引号

PowerShell Hashtable to JSON without Quotes

我正在尝试创建一个散列 table 用作正文 POST 到休息 API。文档列出了 JSON 应该采用的格式,但在 PowerShell 中使用 ConvertTo-Json 时出现一些格式问题。

JSON中有些值不能用引号引起来,有些则需要用引号引起来。我可以使用 $($value) 获取不带引号的静态值输出,但是当该值是现有变量时,这并不相同。

$($variable) 不会像在静态值上那样从 JSON 输出中删除变量上的引号。

当前哈希值table:

$starttime = "1565787600000" #Converted to EPOCH
$endtime = "1597410000000" #Converted to EPOCH

$body = @{}
$body.documentName = "Test.txt"
$body.accessList = @{}
$body.accessList.email = "test@email.com"
$body.accessList.startTime = $starttime  # <--cannot have quotes in json
$body.accessList.endTime = $endtime      # <--cannot have quotes in json

$bodyJson = $body | ConvertTo-Json -Depth 2

输出:

{
    "documentName":  "Test.txt",
    "accessList":  {
                       "email":  "test@email.com",
                       "endTime":  "1597410000000", <--cannot have quotes
                       "startTime":  "1565787600000" <--cannot have quotes
                   }
}

期望的输出:

{
    "documentName":  "Test.txt",
    "accessList":  {
                       "email":  "test@email.com",
                       "endTime":  1597410000000, <--no quotes
                       "startTime":  1565787600000 <--no quotes
                   }
}

您的 POSIX 时间戳被定义为字符串。您需要将它们定义为整数

$starttime = 1565787600000
$endtime = 1597410000000

或者在将数据结构转换为 JSON 之前将字符串转换为整数。

$starttime = "1565787600000"
$endtime = "1597410000000"
...
$body.accessList.startTime = [int64]$starttime
$body.accessList.endTime = [int64]$endtime