【问题标题】:How to use ConvertTo-Json @() on char or string data from PowerShell?如何在 PowerShell 的字符或字符串数​​据上使用 ConvertTo-Json @()?
【发布时间】:2023-04-09 01:13:01
【问题描述】:

convertingJSON 之间的上下文中:

也许下面的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 数据似乎都不可接受。

【问题讨论】:

  • JSON 没有char 类型的概念,只有字符串:ConvertTo-Json @(1,'a')
  • 谢谢,这回答了我的问题(例如)

标签: arrays json powershell type-conversion read-eval-print-loop


【解决方案1】:

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

JSON 值必须是对象、数组、数字或字符串 [...]

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

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

【讨论】:

    猜你喜欢
    • 2013-07-12
    • 2018-11-14
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-31
    • 1970-01-01
    相关资源
    最近更新 更多