2021 年更新:PowerShell 6 和更新版本
PowerShell 6 带来了一个全新的Test-Json
cmdlet。这是参考。
您可以简单地将原始文件内容直接传递给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 及更早版本
这些版本中没有Test-Json
cmdlet,因此最好的方法是将您的ConvertFrom-Json
cmdlet 放在一个try ... catch
块中
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";
}