18

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"
}
dreftymac
  • 31,404
  • 26
  • 119
  • 182
Pulkit
  • 183
  • 1
  • 1
  • 6
  • I can do it by catching the exception. But is there any other way? – Pulkit Jun 11 '13 at 00:49
  • 1
    In PowerShell 6.0, Test-Json Cmdlet is available. https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/test-json?view=powershell-6 – zechariahks Dec 21 '18 at 01:21

5 Answers5

23

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";
}
Naigel
  • 9,086
  • 16
  • 65
  • 106
  • saved my life. trying to figure out an issue where PS4 didn't convert JSON to PSObject with `invoke-restMethod`. you win the internet. – Chaim Eliyah Dec 09 '16 at 18:26
  • Unfortunately, {"a":1,"a":2} passes this test whereas it has duplicate property keys. Most of the parsers don't complain and usually consider the latest property .. However, there is definitely a problem. – Myobis Aug 25 '17 at 14:49
  • 2
    I tried to repeat this functionality with the in-built `Test-Json` with `if(Test-Json $text) {...}`, but I kept getting `Test-Json: Cannot parse the JSON` errors when the file included stuff like `egg` or `{{}`. This solution worked perfectly! Not sure why I couldn't get `Test-Json` to work... – hyperupcall Mar 30 '19 at 23:03
  • 5
    FWIW... test-json was added in PS 6.1 https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/test-json?view=powershell-6 – JeffR Jul 19 '19 at 14:54
  • I included the PS6 solution. Keep in mind that doesn't work for OP since he's on PS3 – Naigel Apr 28 '21 at 07:20
7

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

Robb Vandaveer
  • 1,481
  • 20
  • 25
1

I don't think that it exists an other solution than catching the exception using ConvertFrom-Json.

JPBlanc
  • 70,406
  • 17
  • 130
  • 175
1

ConvertFrom-JSON would work but only for a JSON object < 2MB in size. For higher you can use JavaScriptSerializer class

try
{
    $jsser = New-Object System.Web.Script.Serialization.JavaScriptSerializer
    $jsser.MaxJsonLength = $jsser.MaxJsonLength * 10
    $jsser.RecursionLimit = 99    

    $outObject = $jsser.DeserializeObject($json)
}
catch
{
    Write-Host "Error converting $text to JSON"
}
gsumit10
  • 11
  • 1
0

ConvertFrom-Json shd be the appropriate way to go. Test-Json unfortunately has alot of known unsupported JSON Types. I.E. it cannot parse Json-Arrays or Primitives properly leading to falsely assuming it has wrong JSON-Syntax.