title: How to validate JSON syntax in Powershell before parsing JSON file
body: <p>I am trying to validate the file as JSON complaint, before starting my parsing script. I am trying to catch a Duplicate key or if file is not valid JSOn file. But it seems not working, any help pls:</p>
  
  <pre><code>function ParseFile([string]$file, [int]$domainNumber)
  {
      # read entire JSON file and parse
  
      $bytes = [system.io.file]::ReadAllText($file)
      $json = ConvertFrom-Json $bytes
  
      $text = Get-Content $file -Raw 
  
      try {
          $powershellRepresentation = ConvertFrom-Json $text -ErrorAction Stop;       
          $validJson = $true;
          Write-Error "IN TRY";
      } catch {
          Write-Error "IN CATCH";
          $validJson = $false;
      }
  
  
      if ($validJson) {
          Write-Error "Provided text has been correctly parsed to JSON";
          Exit 1
      } else {
          Write-Error "Provided text is not a JSON valid string";
          Exit 1
      } 
  </code></pre>
  
  <p>It always says the file is valid JSON, even the file contains the duplicate key. CALL powershell.exe -noprofile -executionpolicy bypass -file D:\Tools\Scripts json_files\config.pkg.xml ParseFile : 111 At D:\Tools\Scripts\json.ps1:110 char:4 + ParseFile $file $domainNumber + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,ParseFile</p>
  
  <p>ParseFile : 2222 At D:\Tools\Scripts\json.ps1:110 char:4 + ParseFile $file $domainNumber + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,ParseFile</p>
  
  <p>ParseFile : Provided text has been correctly parsed to JSON At D:\Tools\Scripts\json.ps1:110 char:4 + ParseFile $file $domainNumber + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,ParseFile</p>
  
  <p><a href="https://stackoverflow.com/questions/17034954/how-to-check-if-file-has-valid-json-syntax-in-powershell/42270096?noredirect=1#comment71697563_42270096">How to check if file has valid JSON syntax in Powershell</a> </p>
  
  <hr>
  
  <p>Sample :</p>
  
  <pre><code>{
    "sr_version": {
      "major": 1,
      "minor": 1,
      "patch": 1
    },
    "sr_domain": {
      "soc": "msm",
      "domain": "Audio",
      "subdomain": "root",
      "qmi_instance_id": 74
    },
    "sr_domain": {
      "soc": "msm",
      "domain": "Audio",
      "subdomain": "root",
      "qmi_instance_id": 74
    },
    "sr_service": [{
      "provider": "tms",
      "service": "servreg",
      "service_data_valid": 0,
      "service_data": 0
    }]
  }
  </code></pre>