json - ConvertTo-Json 拆箱单品
问题描述
我在 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-字符串
但是当它只包含一个项目时,我不知道如何只针对那个键。
解决方案
您要确保所有哈希表值都是数组(这就是哈希表输出中的大括号和 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)
问题就会消失。
推荐阅读
- youtube-data-api - 评论列表片段中未返回 videoId
- google-cloud-monitoring - 在 Cloud 任务队列中有超过一定数量的任务且重试值 > 0 时触发 GCP 监控中的警报
- azure-log-analytics - Azure Log Analytics:无法解析表或列或标量表达式
- generics - 移出泛型类型的共享引用
- python - Python中的“dummy_func”是什么
- visual-studio-code - 在命令提示符下运行 Python 文件会启动 vscode
- php - 如何将 HTML 值传递给 PHP 变量
- tomcat - 在 openshift 上的 Coldfusion 中更新 Tomcat 的 server.xml 文件
- javascript - Google Visualization ChartWrapper 以编程方式设置单元格值
- javascript - 刷新页面后保留LocalStorage