How to check if file has valid JSON syntax in Powershell

送分小仙女□ 提交于 2019-12-12 10:35:03

问题


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

回答1:


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



回答2:


If you encounter this question and can use PowerShell 6 or later, there is now a Test-Json cmdlet. It can also not just validate that it's valid JSON, but that it conforms to a particular JSON schema using the -Schema param.

Example

$isValid = Get-Content .\filename.txt -Raw | Test-Json 

if($isValid){
 Write-Host "not JSON"
}
else{
 Write-Host "True"
}

ARM Template Warning

A note for users looking to validate an ARM template via -Schema (I can't imagine a more perfect use case). At the time of writing, there are one or more bugs in the underlying library Test-Json uses for validation, NJsonSchema, and it is not possible to validate an ARM template.

GitHub Issues

  • PowerShell Issue #9560
  • NJsonSchema Issue #588



回答3:


I don't think that it exists an other solution than catching the exception using ConvertFrom-Json.




回答4:


ConvertFrom-JSON would work but only for a JSON object < 2MB in size. For higher you can use JavaScriptSerializer class

try
{
    $jsser = New-Object System.Web.Script.Serialization.JavaScriptSerializer
    $jsser.MaxJsonLength = $jsser.MaxJsonLength * 10
    $jsser.RecursionLimit = 99    

    $outObject = $jsser.DeserializeObject($json)
}
catch
{
    Write-Host "Error converting $text to JSON"
}


来源:https://stackoverflow.com/questions/17034954/how-to-check-if-file-has-valid-json-syntax-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!