如何将存储在 JSON 文件中的数据加载到 power shell 中的数组或散列 table 中?
How to load the data stored in a JSON file into an array or an hash table in 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"
}
]
如果你有一个 JSON 文件,里面有一个 JSON 数组,你需要做的就是将该文件读入一个字符串并将其传递给 ConvertFrom-Json
。这将在 PowerShell 中生成一组自定义对象。
Get-Content 'C:\path\to\input.json' | Out-String | ConvertFrom-Json
在 PowerShell v3 或更高版本中,您可以通过将参数 -Raw
添加到 Get-Content
:
来替换 Out-String
步骤
Get-Content 'C:\path\to\input.json' -Raw | ConvertFrom-Json
在 Powershell v6 中,built-in 和 ConvertFrom-Json 存储为 hash-table:
Get-Content 'C:\path\to\input.json' | ConvertFrom-Json -AsHashtable
我想将 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"
}
]
如果你有一个 JSON 文件,里面有一个 JSON 数组,你需要做的就是将该文件读入一个字符串并将其传递给 ConvertFrom-Json
。这将在 PowerShell 中生成一组自定义对象。
Get-Content 'C:\path\to\input.json' | Out-String | ConvertFrom-Json
在 PowerShell v3 或更高版本中,您可以通过将参数 -Raw
添加到 Get-Content
:
Out-String
步骤
Get-Content 'C:\path\to\input.json' -Raw | ConvertFrom-Json
在 Powershell v6 中,built-in 和 ConvertFrom-Json 存储为 hash-table:
Get-Content 'C:\path\to\input.json' | ConvertFrom-Json -AsHashtable