Parse JSON in PowerShell with Clear Error Messages
PowerShell
function ConvertFrom-JsonSafe {
param(
[Parameter(Mandatory, ValueFromPipeline)][AllowEmptyString()][string]$Json,
[ValidateRange(1, 64)][int]$Depth = 32
)
process {
if ([string]::IsNullOrWhiteSpace($Json)) { throw 'Cannot parse JSON: input is empty.' }
try {
$Json | ConvertFrom-Json -Depth $Depth -ErrorAction Stop
} catch {
$message = $_.Exception.Message
$where = if ($message -match 'position (\d+)') { " at position $($Matches[1])" } else { '' }
throw "Invalid JSON$($where): $message"
}
}
}