Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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;
like image 430
ComFreek Avatar asked Aug 27 '12 10:08

ComFreek


2 Answers

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.

like image 127
Shay Levy Avatar answered Oct 14 '22 02:10

Shay Levy


Alternatively you can use Get-Content -Raw which will retrieve the JSON as a single string.

See this post for more info: http://blogs.technet.com/b/heyscriptingguy/archive/2014/04/23/json-is-the-new-xml.aspx

like image 10
Alasdair Ross Avatar answered Oct 14 '22 03:10

Alasdair Ross