如何在Powershell中检查文件是否具有有效的JSON语法 [英] How to check if file has valid JSON syntax in Powershell
本文介绍了如何在Powershell中检查文件是否具有有效的JSON语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个Powershell脚本,该脚本读取一个文件,如果它是有效的JSON文件,则显示"true".我正在使用Powershell v3.0,这是我现在拥有的:
I am trying to write a powershell script that reads a file and prints "true" if it is a valid JSON file. I am using Powershell v3.0 and this is what I have right now :
$text = Get-Content .\filename.txt -Raw
$powershellRepresentation = $text | ConvertFrom-Json
如何检查返回码?我的意思是我想要这样的东西:
How do I check the return code? I mean I want something like this :
if(file not a JSON file){
Write-Host "not JSON"
}
else{
Write-Host "True"
}
推荐答案
没有像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";
}
这篇关于如何在Powershell中检查文件是否具有有效的JSON语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文