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:
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
    } 
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
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
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
How to check if file has valid JSON syntax in Powershell
Sample :
{
  "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
  }]
}
 
     
    