Search code examples
powershellhashtable

PowerShell Hashtable to JSON without Quotes


I am trying to create a hash table to use as the body to POST to a rest API. The documentation listed the format for the JSON should be in, but having some formatting problems when using ConvertTo-Json in PowerShell.

Some of the values in JSON cannot be in quotes, and some need to be in quotes. I can get static values to output without quotes using $($value), but this does not work the same when the value is an existing variable.

$($variable) does not remove quotes on variables from JSON output like it does on static values.

Current hash 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

Output:

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

Desired output:

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

Solution

  • Your POSIX timestamps are defined as strings. You need to either define them as integers

    $starttime = 1565787600000
    $endtime = 1597410000000
    

    or turn the strings into integers before converting your data structure to JSON.

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