解析JSON时"传递了无效数组"

Com*_*eek 16 powershell json powershell-3.0

我有这个文件,我想用PowerShell阅读:

var myMap =
[
  {
    "name": "JSON Example",
    "attr": "Another attribute"
  }
]
Run Code Online (Sandbox Code Playgroud)

我的PowerShell v3代码:

$str = Get-Content $file | Select -Skip 1;
$str | ConvertFrom-Json;
Run Code Online (Sandbox Code Playgroud)

但我总是得到这个错误:

ConvertFrom-Json : Invalid array passed in, ']' expected. (1): [
At S:\ome\Path\script.ps1:60 char:8
+ $str | ConvertFrom-Json;
+        ~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [ConvertFrom-Json], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand
Run Code Online (Sandbox Code Playgroud)

如果我手动将JSON代码复制并粘贴到代码中,一切正常:

'[
  {
    "name": "JSON Example",
    "attr": "Another attribute"
  }
]' | ConvertFrom-Json;
Run Code Online (Sandbox Code Playgroud)

Sha*_*evy 32

在管道到Out-String之前尝试管道ConvertFrom-Json:

Get-Content $file | Select -Skip 1 | Out-String | ConvertFrom-Json
Run Code Online (Sandbox Code Playgroud)

在您的工作示例中,JSON代码是一个字符串,而非工作示例返回一组行.用于Out-String将集合转换为单个字符串的管道,这是InputObject参数接受的.


Ala*_*oss 9

或者,您可以使用Get-Content -Raw它将JSON检索为单个字符串.

有关详细信息,请参阅此帖子:http://blogs.technet.com/b/heyscriptingguy/archive/2014/04/23/json-is-the-new-xml.aspx