How to check if file has valid JSON syntax in Powershell

Pulkit picture Pulkit · Jun 11, 2013 · Viewed 12.1k times · Source

I am trying to write a powershell script that reads a file and prints "true" if it is a valid JSON file. I am using Powershell v3.0 and this is what I have right now :

$text = Get-Content .\filename.txt -Raw 
$powershellRepresentation = $text | ConvertFrom-Json

How do I check the return code? I mean I want something like this :

if(file not a JSON file){
 Write-Host "not JSON"
}
else{
 Write-Host "True"
}

Answer

Naigel picture Naigel · Jun 18, 2013

There isn't a Test-Json like cmdlet, so the best way is to put your ConvertFrom-Json cmdlet inside a try ... catch block

try {
    $powershellRepresentation = ConvertFrom-Json $text -ErrorAction Stop;
    $validJson = $true;
} catch {
    $validJson = $false;
}

if ($validJson) {
    Write-Host "Provided text has been correctly parsed to JSON";
} else {
    Write-Host "Provided text is not a valid JSON string";
}