如何在 PowerShell 的字符或字符串数​​据上使用 ConvertTo-Json @()?

How to use ConvertTo-Json @() on char or string data from PowerShell?

的上下文中往返于 JSON:

也许下面的integer只是标记数组索引?然而,发送 1,1,1 是完全可能的,所以它不是索引。那么“1”可能表示“深度”?

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> 

为什么整数可以:

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

但连一个都没有char?

String 数据似乎都不可接受。

PowerShell 没有任何用于定义字符文字的语法,并且裸词(如您示例中的 a)被解释为命令,如错误所示。

如果要将单个 [char] a 作为值传递,有多种选择:

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

# Index into string
'a'[0]

# Convert from numberic value
97 -as [char]

所以你可以这样做:

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

但是您会注意到,生成的 JSON 似乎已将 [char] 转换回字符串 - 那是因为 JSON 的语法没有 [char]的任一个。

来自RFC 8259 §3

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

所以从 [string] 转换为 [char] 实际上是完全多余的:

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