Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if file has valid JSON syntax in Powershell

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"
}
like image 936
Pulkit Avatar asked Jun 11 '13 00:06

Pulkit


People also ask

How do you check if a file is a valid JSON file?

The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JSchema) method with the JSON Schema. To get validation error messages use the IsValid(JToken, JSchema, IList<String> ) or Validate(JToken, JSchema, SchemaValidationEventHandler) overloads.

Can PowerShell read JSON?

PowerShell is a great tool to use for manipulating JSON which is used throughout Azure. Have fun scripting! Additional reading: 7.1: ConvertFrom-Json (Microsoft.


1 Answers

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";
}
like image 97
Naigel Avatar answered Sep 17 '22 19:09

Naigel