-2

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
                   }
}
Chase
  • 1
  • 3
  • 4
    DateTime is not a type in JSON.. it would be an error to not have quotes. – Maximilian Burszley Aug 14 '19 at 14:30
  • I just checked the order on PSv5.1/6.2.2 on Win10/Ubuntu/MacOS pasting the very same code and ***every*** instance had a different order - but who cares / what does it matter for a primarily m2m format? –  Aug 14 '19 at 14:54
  • The actual value will be in EPOCH, but either way, I'm looking to see how to remove the quotes regardless of the value. The above code is just an example. – Chase Aug 14 '19 at 14:56
  • For the order see: [Hashtables and key order](https://stackoverflow.com/a/14891153/1701026) – iRon Aug 14 '19 at 14:56
  • Your change from a string to an int totally changed the issue and makes your title now a bit misleading. –  Aug 14 '19 at 16:24

1 Answers1

2

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
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328