1

In the context of converting to and from JSON:

perhaps the integer's below are just marking array index? Yet it's entirely possible to send 1,1,1 so it's not an index. the "1" might, perhaps, indicate a "depth" then?

PS /home/nicholas/powershell> 
PS /home/nicholas/powershell> ConvertTo-Json @(1)  
[
  1
]
PS /home/nicholas/powershell> 
PS /home/nicholas/powershell> ConvertTo-Json @(1,a)
ParserError: 
Line |
   1 |  ConvertTo-Json @(1,a)
     |                     ~
     | Missing expression after ','.

PS /home/nicholas/powershell> 
PS /home/nicholas/powershell> ConvertTo-Json @(1,2)
[
  1,
  2
]
PS /home/nicholas/powershell> 
PS /home/nicholas/powershell> ConvertTo-Json @(a)  
a: The term 'a' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
[]
PS /home/nicholas/powershell> 

why are integers okay:

PS /home/nicholas/powershell> 
PS /home/nicholas/powershell> ConvertTo-Json @(1,3,9)
[
  1,
  3,
  9
]
PS /home/nicholas/powershell> 

but not even a single char?

Neither it seems are String data acceptable.

1 Answers1

3

PowerShell doesn't have any syntax for defining character literals, and bare words (like the a in your example) are interpreted as commands, as the error indicates.

If you want to pass the a single [char] a as a value, there are a number of options:

# Convert single-char string to char
[char]'a'
# or
'a' -as [char]

# Index into string
'a'[0]

# Convert from numberic value
97 -as [char]

So you could do something like this:

PS ~> ConvertTo-Json @(1,'a'[0])
[
    1,
    "a"
]

But as you'll notice, the resulting JSON appears to have converted the [char] back into a string - and that's because JSON's grammar doesn't have [char]'s either.

From RFC 8259 §3:

A JSON value MUST be an object, array, number, or string [...]

So converting from [string] to [char] is in fact completely redundant:

PS ~> ConvertTo-Json @(1,'a')
[
    1,
    "a"
]
Community
  • 1
  • 1
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206