首页 > 解决方案 > ConvertTo-Json 拆箱单品

问题描述

我在 PowerShell 中使用这样的哈希表:

哈希表

当我将其转换为 JSON 时,请注意“oranges”键不包含括号:

JSON1

当我通过执行以下操作创建哈希表时,我试图适应这一点:

foreach ($Group in ($input | Group fruit)) {
    if ($Group.Count -eq 1) {
        $hashtable[$Group.Name] = "{" + ($Group.Group | Select -Expand number) + "}"
    } else {
        $hashtable[$Group.Name] = ($Group.Group | Select -Expand number)
    }
}

当我将它输出为哈希表时看起来不错,但是当我转换为 JSON 时,我得到了这个:

JSON2

我正在尝试将单个项目也包围在[]. 我在这里发现了一些东西,其中之一把我带到了这个: https ://superuser.com/questions/414650/why-does-powershell-silently-convert-a-string-array-with-one-item-to -a-字符串

但是当它只包含一个项目时,我不知道如何只针对那个键。

标签: jsonpowershell

解决方案


您要确保所有哈希表值都是数组(这就是哈希表输出中的大括号和 JSON 中的方括号的含义)。

更改此代码:

if ($Group.Count -eq 1) {
    $hashtable[$Group.Name] = "{" + ($Group.Group | Select -Expand number) + "}"
} else {
    $hashtable[$Group.Name] = ($Group.Group | Select -Expand number)
}

进入这个:

$hashtable[$Group.Name] = @($Group.Group | Select -Expand number)

问题就会消失。


推荐阅读