【问题标题】:How to check if file has valid JSON syntax in Powershell如何在 Powershell 中检查文件是否具有有效的 JSON 语法
【发布时间】:2013-06-06 18:17:53
【问题描述】:

我正在尝试编写一个 powershell 脚本来读取文件并在它是有效的 JSON 文件时打印“true”。我正在使用 Powershell v3.0,这就是我现在所拥有的:

$text = Get-Content .\filename.txt -Raw 
$powershellRepresentation = $text | ConvertFrom-Json

如何查看返回码?我的意思是我想要这样的东西:

if(file not a JSON file){
 Write-Host "not JSON"
}
else{
 Write-Host "True"
}

【问题讨论】:

标签: json powershell try-catch powershell-3.0


【解决方案1】:

2021 年更新:PowerShell 6 及更新版本

PowerShell 6 带来了全新的Test-Json cmdlet。 Here is the reference.

您可以简单地将原始文件内容直接传递给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";
}

【讨论】:

  • 救了我的命。试图找出 PS4 没有使用invoke-restMethod 将 JSON 转换为 PSObject 的问题。你赢得了互联网。
  • 不幸的是,{"a":1,"a":2} 通过了这个测试,而它有重复的属性键。大多数解析器不会抱怨,通常会考虑最新的属性..但是,肯定有问题。
  • 我尝试使用内置的Test-Jsonif(Test-Json $text) {...} 重复此功能,但是当文件包含egg{{} 之类的内容时,我不断收到Test-Json: Cannot parse the JSON 错误。该解决方案完美运行!不知道为什么我不能让Test-Json 工作......
  • FWIW... test-json 已添加到 PS 6.1 docs.microsoft.com/en-us/powershell/module/…
  • 此答案已过时,请对 Robb 最新的答案进行投票和投票。
【解决方案2】:

如果您遇到这个问题并且可以使用 PowerShell 6 或更高版本,现在有一个 Test-Json cmdlet。它不仅可以验证它是有效的 JSON,还可以使用 -Schema 参数验证它是否符合特定的 JSON 模式。

示例

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

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

ARM 模板警告

为希望通过-Schema 验证 ARM 模板的用户提供的说明(我无法想象更完美的用例)。在撰写本文时,Test-Json 用于验证的底层库 NJsonSchema 中存在一个或多个错误,并且无法验证 ARM 模板。

GitHub 问题

【讨论】:

    【解决方案3】:

    我认为除了使用ConvertFrom-Json 捕获异常之外,没有其他解决方案。

    【讨论】:

      【解决方案4】:

      ConvertFrom-JSON 可以工作,但仅适用于小于 2MB 的 JSON 对象。 对于更高版本,您可以使用 JavaScriptSerializer 类

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

      【讨论】:

        猜你喜欢
        • 2015-09-28
        • 2013-12-07
        • 1970-01-01
        • 1970-01-01
        • 2015-11-26
        • 2010-10-27
        • 2018-08-31
        相关资源
        最近更新 更多