UPDATE 2021: PowerShell 6 and newer versions
PowerShell 6 brings a brand new Test-Json
cmdlet. Here is the reference.
You can simply pass the raw file content directly to the Test-Json
cmdlet.
$text = Get-Content .\filename.txt -Raw
if ($text | Test-Json) {
$powershellRepresentation = ConvertFrom-Json $text -ErrorAction Stop;
Write-Host "Provided text has been correctly parsed to JSON";
} else {
Write-Host "Provided text is not a valid JSON string";
}
PowerShell 5 and earlier versions
There is no Test-Json
cmdlet in these versions, 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";
}