Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConvertFrom-Json : Invalid JSON primitive:

I was trying to run a script that fetches JSON file from CMS endpoint, pass it on the pipeline to convertfrom-json. But, I get an error saying Invalid JSON primitive.

ConvertFrom-Json : Invalid JSON primitive: . At D:\AzureProject\SetupusingParameterfile.ps1:13 char:75

 $JsonContent = Get-Content $TemplateParameterFileLocal -Raw | Conver ...

CategoryInfo : NotSpecified: (:) [ConvertFrom-Json], ArgumentException + FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand

Structure of my JSON Parameter file was inline to how Azure Parameter file structure needs to be and sample is as below:-

{
"$schema": "http://schema.management.azure.com/schemas/20111-01-01/deploymentParameters.json#",
"contentVersion":"1.0.0.0",
"parameters": 
        {
            "hostingPlanName": {"value": "pilotHosting"},
            "hostingEnvironment": {"value": "pilotHostingenv"},   
            "serverFarmResourceGroup": {"value": "Pilot1H"},
            "sqlserverName": {"value": "pilotsrvrtrialrun11"},
            "administratorLogin": {"value": "sites1H"},
            "administratorLoginPassword": {"value": "abcdefg"},
            "serverName": {"value": "Pilotwebserver"},
            "databaseUsername": {"value": "pilot1Hattabc"},
            "databasePassword": {"value": "pilotdbabc1H"},
        }
}

Note: The purpose of this post is to share few things that came up during Azure project PoC, and hope to serve someone later.

like image 811
H Bala Avatar asked Jun 01 '16 03:06

H Bala


2 Answers

Approach 1 : -Raw Attempted using -Raw with Get-Content so that Get-Content instead of reading each line separately and storing as array, creates object.

 $JsonContent = Get-Content $TemplateParameterFileLocal -Raw | ConvertFrom-Json

Approach 2 : Out-String Attempted with Get-Content piped to | Out-String as below:

$JsonContent = Get-Content $TemplateParameterFileLocal | Out-String | ConvertFrom-Json

Review JSON with IDE Finally, I recollected the IDE notification when I had opened up the saved copy of CMS generated JSON. It had a EOF expected but if you notice the above JSON structure, it got a ',' which was causing this trouble.

I tried both -Raw and Out-String execution again, and it was working as expected.

like image 122
H Bala Avatar answered Sep 18 '22 21:09

H Bala


You may also have this problem with an old version of PowerShell (5.1) if your json contains a trailing comma.

PowerShell 5.1: ❌
PowerShell Core 7.1.3: ✔

{
  "Key": "Value",
}

Error in 5.1:

ConvertFrom-Json : Invalid JSON primitive: .

PowerShell 5.1: ✔

{
  "Key": "Value"
}
like image 29
ded' Avatar answered Sep 20 '22 21:09

ded'