Assert-JsonValidity.psm1
# Validate JSON Parameter passed to the runbook to ensure there is no errors function Assert-JsonValidity() { # Workaround for Powershell 7.1 as there is known issue causing Webhook invocation to break JSON, so lets fix it without breaking it in future [CmdletBinding()] Param([Parameter(Mandatory = $True, ValueFromPipeline = $True, ValueFromPipelinebyPropertyName = $True)][Object]$Json) # Checks if the content is valid json already, or if not then will run string replacement on it $ValidateJson = $Json | Test-Json -ErrorAction SilentlyContinue if (-Not ($ValidateJson)) { $Json = $Json -replace ',', '","' -replace ':', '":"' -replace '}', '"}' -replace '{', '{"' -replace ':"{', ':{' -replace '"}', '}' -replace '\/}', '/"}' -replace '}",', '},' # after string replace runs to check if its valid now if not then either another missing replace is needed or its not JSON $ValidateJson = $Json | Test-Json -ErrorAction SilentlyContinue if ($ValidateJson) { Write-Verbose -Message "`$Json is valid JSON" Write-Verbose -Message "`$Json:`n$Json`n" $Json = $Json | ConvertFrom-Json return $Json } else { Write-Error -Message "`$Json is not a valid, ensure there is no missing replacements still needed.`n`n`$Json:`n$Json`n`nError:`n$_" -ErrorAction Stop } } # Test returned valid json so ConvertFrom-Json makes it a usable object same as it was in 5.1 else { Write-Verbose -Message "`$Json is Valid JSON and converting to an Object" $Json = $Json | ConvertFrom-Json return $Json } } Export-ModuleMember -Function Assert-JsonValidity |