ComFreek ComFreek - 1 year ago 273
JSON Question

"Invalid array passed" when parsing JSON

I have this file which I want to read with PowerShell:

var myMap =
"name": "JSON Example",
"attr": "Another attribute"

My PowerShell v3 Code:

$str = Get-Content $file | Select -Skip 1;
$str | ConvertFrom-Json;

But I'm always getting this error:

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

If I copy and paste the JSON code manually into the code, everything is working fine:

"name": "JSON Example",
"attr": "Another attribute"
]' | ConvertFrom-Json;

Answer Source

Try to pipe to Out-String before piping to ConvertFrom-Json:

Get-Content $file | Select -Skip 1 | Out-String | ConvertFrom-Json

In your working example the JSON code is a string while the non-working example returns a collection of lines. Piping to Out-String converts the collection to a single string, which is what the InputObject parameter accept.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download