Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Invalid JSON primitive" error when converting JSON file

Tags:

When trying to convert a JSON file via PowerShell:

$json = Get-Content "C:\folder1\test.txt"  $json | ConvertFrom-Json   write-output $json 

I'm getting the following error:

invalid json primitive : [.
(system.argunment.exception)

like image 790
user3770612 Avatar asked Jun 27 '14 13:06

user3770612


People also ask

What does an invalid JSON mean?

It means that the editor failed to get a response to the server or the response wasn't in a valid JSON format. Basically, if the editor can't communicate with the server, it will show this error message instead. To fix the problem, you essentially need to fix whatever is getting in the way of the communication.


2 Answers

I'm going out on a limb here, since you didn't provide your input data or the complete error message, but I guess that your problem is caused by a format mismatch between the output Get-Content provides and the input ConvertFrom-Json expects.

Get-Content reads the input file into an array of strings, whereas ConvertFrom-Json expects the JSON data in a single string. Also, piping $json into ConvertFrom-Json does not change the value of $json.

Change your code to the following and the error should disapear (provided there is no syntactical error in your input data):

$json = Get-Content 'C:\folder1\test.txt' | Out-String | ConvertFrom-Json  Write-Output $json 
like image 157
Ansgar Wiechers Avatar answered Oct 29 '22 06:10

Ansgar Wiechers


You should check your JSON input file for characters that are not properly escaped with a "\"

I have also seen this issue with an input JSON file that was incorrectly formatted as follows:

{     Object1 } {     Object2 } 

Corrected format:

[{      Object1  },  {       Object2  }] 

Once the format was corrected, I had no more issues.

like image 34
itrjll Avatar answered Oct 29 '22 06:10

itrjll