How to check if file has valid JSON syntax in Powershell
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 -Rawif ($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";}
If you encounter this question and can use PowerShell 6 or later, there is now a Test-Json cmdlet. It can also not just validate that it's valid JSON, but that it conforms to a particular JSON schema using the -Schema
param.
Example
$isValid = Get-Content .\filename.txt -Raw | Test-Json if($isValid){ Write-Host "not JSON"}else{ Write-Host "True"}
ARM Template Warning
A note for users looking to validate an ARM template via -Schema
(I can't imagine a more perfect use case). At the time of writing, there are one or more bugs in the underlying library Test-Json
uses for validation, NJsonSchema, and it is not possible to validate an ARM template.
GitHub Issues
I don't think that it exists an other solution than catching the exception using ConvertFrom-Json
.