且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Powershell中检查文件是否具有有效的JSON语法

更新时间:2023-11-26 09:40:10

没有像cmdlet这样的Test-Json,所以***的方法是将ConvertFrom-Json cmdlet放在try ... catch块内

There isn't a Test-Json like cmdlet, so the best way is to put your ConvertFrom-Json cmdlet inside a try ... catch block

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";
}