Powershell ConvertFrom-Json 意外地从包含字符串的单个项目数组生成字符串而不是对象数组

2024-02-07

文件“array.json”:[“bogus”]

PS C:\Users\Me> (Get-Content "array.json" | ConvertFrom-Json -NoEnumerate).GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

PS C:\Users\Me> (Get-Content "array.json" | ConvertFrom-Json).GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

虽然有时可能有用,但绝对不是我意想不到的。下面发布的答案可以帮助其他人并避免混淆。


在 PowerShell 中,单个项目数组在返回时展开,请参阅:关于数组你想知道的一切 https://learn.microsoft.com/powershell/scripting/learn/deep-dives/everything-about-arrays.

写输出-NoEnumerate https://learn.microsoft.com/powershell/scripting/learn/deep-dives/everything-about-arrays#write-output--noenumerate

PowerShell 喜欢解开或枚举数组。这是 PowerShell 使用管道方式的核心方面,但有时您不希望这种情况发生。

这可能是最大的陷阱/陷阱 https://stackoverflow.com/q/11107428/1701026在 PowerShell 中并且不特定于ConvertFrom-Json https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/convertfrom-jsoncmdlet,请参阅例如:当调用仅返回一个对象时,如何强制 Powershell 返回一个数组? https://stackoverflow.com/q/11107428/1701026.

强制数组的最简单(也是最常见)的方法是使用数组子表达式运算符@( ) https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_operators#array-subexpression-operator--(而不是分组运算符( ) https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_operators#grouping-operator--):

@('["bogus"]' | ConvertFrom-Json).GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

e.g.:

@('["bogus"]' | ConvertFrom-Json)[0]
bogus

另请参阅以下问题:展开数组单个“数组子表达式运算符” https://stackoverflow.com/search?q=%5Bpowershell%5D+unroll+array+single+%22Array+subexpression+operator%22

As 马克门0 https://stackoverflow.com/users/45375/mklement0指出这有帮助ConvertFrom-Json 解压包含 1 个项目的数组,并且对于空对象表现奇怪 https://stackoverflow.com/a/76996546/1701026答案,您可能还会注意到此行为与 PowerShell 7+ 之前的版本之间的差异。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Powershell ConvertFrom-Json 意外地从包含字符串的单个项目数组生成字符串而不是对象数组 的相关文章

随机推荐