首页 > 解决方案 > 如何将存储在 JSON 文件中的数据加载到 power shell 中的数组或哈希表中?

问题描述

我想将 JSON 文件中的数据加载到数组中。JSON 文件中的数据是一个数组数组。加载后,数组不应有额外的字符,如 \r、\n。

我该怎么做?以下是文件的内容。我希望它作为数组而不是字符串加载。

[
{
    "CRLDps":  [
                   "http://crl.pki.goog/GTSGIAG3.crl"
               ],
    "aliasName":  "Google Internet Authority G3",
    "commonName":  "Google Internet Authority G3"
},
{
    "CRLDps":  [
                   "http://crl.globalsign.com/gs/gsorganizationvalsha2g2.crl"
               ],
    "aliasName":  "GlobalSign Organization Validation CA - SHA256 - G2",
    "commonName":  "GlobalSign Organization Validation CA - SHA256 - G2"
}
]

标签: powershellpowershell-2.0powershell-3.0

解决方案


如果您有一个带有 JSON 数组的 JSON 文件,您需要做的就是将该文件读入单个字符串并将其传递到ConvertFrom-Json. 这将在 PowerShell 中生成一组自定义对象。

Get-Content 'C:\path\to\input.json' | Out-String | ConvertFrom-Json

在 PowerShell v3 或更高版本中,您可以Out-String通过将参数添加-Raw到以下步骤来替换该步骤Get-Content

Get-Content 'C:\path\to\input.json' -Raw | ConvertFrom-Json

推荐阅读