【问题标题】:ConvertTo-Json unboxing single itemConvertTo-Json 拆箱单品
【发布时间】:2018-11-26 22:00:07
【问题描述】:

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

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

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

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 时,我得到了这个:

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

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

【问题讨论】:

    标签: json powershell


    【解决方案1】:

    您要确保所有哈希表值都是数组(这就是哈希表输出中的大括号和 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)
    

    问题就会消失。

    【讨论】:

    • 成功了!我曾尝试过一种不同的变体,但我把它用引号括起来。非常感谢你!还要感谢您解释大括号和方括号,因为我不知道。
    猜你喜欢
    • 2013-10-02
    • 1970-01-01
    • 2021-12-31
    • 2013-09-10
    • 2015-03-20
    • 2015-05-25
    • 1970-01-01
    • 2021-09-04
    • 2013-03-12
    相关资源
    最近更新 更多