powershell - ConvertFrom-Json 解压包含 1 个项目的数组,并且对于空对象表现奇怪

标签 powershell powershell-7

我正在尝试找出如何阻止 ConvertFrom-Json 解包数组类型(如果它们有一个或零个项目)。

我已阅读这些相关帖子: ConvertTo-JSON an array with a single item How to prevent ConvertFrom-Json from collapsing nested arrays if there's 1 element

读完这些内容后,我认为我没有遇到成员访问枚举,因为我没有使用访问运算符。

我尝试在不使用管道的情况下使用 ConvertFrom-Json,但这并没有像使用 ConvertTo-Json 的人那样解决问题

这是一个带有输出的简单示例:

$x = '[{"a": 1, "b": 2}]'
$y = ConvertFrom-Json -InputObject $x

$a = '[]'
$b = ConvertFrom-Json -InputObject $a

Write-Host $y -ForegroundColor Green
Write-Host $y.GetType() -ForegroundColor Green

Write-Host $b -ForegroundColor Green
Write-Host $b.GetType() -ForegroundColor Green
@{a=1; b=2} # first object in array, not array
System.Management.Automation.PSCustomObject # treats as object instead of array
# nothing was printed here because b is null
InvalidOperation: C:\Users\username\Test.ps1:11:1 # error from trying to print the type of b
Line |
  11 |  Write-Host $b.GetType() -ForegroundColor Green
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | You cannot call a method on a null-valued expression.

我期望的输出类型是返回 System.Object[]GetType() 调用

其他上下文:

我正在使用 github cli 获取不同存储库的 PR 列表,并为某些内部工作流程聚合一些数据。显然,一个存储库可能有 0、1 或更多 PR,我希望避免 0 或 1 情况的任何特殊逻辑,因为空数组或包含一项的数组可以遵循与数组相同的代码路径许多项目。

最佳答案

您看到的行为表明您使用的是 PowerShell (Core) 7+,而不是 Windows PowerShell。

虽然您的命令恰好在 Windows PowerShell 中工作,但它依赖于违反通常管道行为的行为,即枚举数组 - 请参阅(现已关闭)GitHub issue #3424背景信息。

正是出于这个原因,在 PowerShell 7+ 中,ConvertFrom-Json 现在默认枚举从 JSON 数组解析的元素,并且需要按顺序选择加入使用 -NoEnumerate 开关请求将这样的数组作为单个对象输出:

$x = '[{"a": 1, "b": 2}]'

# Note the -NoEnumerate switch (v7+)
$y = ConvertFrom-Json -NoEnumerate -InputObject $x

$y.GetType().Name # -> 'Object[]', proving that the array was preserved.

关于powershell - ConvertFrom-Json 解压包含 1 个项目的数组,并且对于空对象表现奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76996473/

相关文章:

c# - 在 PowerShell 中隐式转换为 C# 中定义的结构的 bool 失败

c# - 你能捕捉到使用Powershell调用C#控制台应用抛出的错误码和异常信息吗?

regex - 为什么这个正则表达式无法匹配第二个 6 位数字?

sharepoint - 在SharePoint Online中使用Powershell更改列表字段

powershell - 如何在FTP服务器中移动文件