You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在PowerShell中用Test-Json验证JSON Schema是否符合draft-07规范

JSON Schema draft-07合法性校验Test-Json报错解决方案

问题原因

1. 操作笔误

你执行Get-Content读取draft07schema.json时路径填写错误,重复拼接了两次C:\temp前缀,C:\temp\c:\temp\draft07schema.json属于无效路径,首先修正路径后再重试。

2. Test-Json固有局限

如果修正路径后仍抛出Cannot parse the JSON schema错误,属于PowerShell内置Test-Json cmdlet的已知问题:
Test-Json底层依赖NJsonSchema库实现校验,对draft-07元Schema(即用来校验Schema本身的官方规范文件)中$recursiveRef等递归引用语法的解析支持不完善,因此无法直接将draft-07元Schema作为校验规则使用。

适配自动化/PR校验的解决方案

方案1:使用ajv-cli(推荐,兼容性最好)

ajv是目前JSON Schema规范支持最完整的校验工具,适合集成到CI流程:

  1. 安装Node.js后执行命令全局安装ajv-cli:
    npm install -g ajv-cli
  2. 执行校验命令:
    ajv validate -s c:\temp\draft07schema.json -d c:\temp\testschema.json
    返回pass即为合规,返回错误即为不符合规范。

方案2:PowerShell原生调用NJsonSchema API

如果不能引入Node.js依赖,可以直接调用Test-Json依赖的NJsonSchema底层API绕过上层限制:

# 安装NJsonSchema包(首次运行执行即可)
Install-Package NJsonSchema -Version 10.9.0 -Source nuget.org
# 读取待校验的Schema文件
$testSchema = Get-Content "c:\temp\testschema.json" -Raw
# 解析并校验Schema合法性
$schemaObj = [NJsonSchema.JsonSchema]::FromJsonAsync($testSchema).GetAwaiter().GetResult()
$validationErrors = $schemaObj.Validate()
# 输出校验结果
if ($validationErrors.Count -eq 0) {
    Write-Host "Schema符合draft-07规范"
    exit 0
} else {
    Write-Host "Schema不符合draft-07规范,错误信息:"
    $validationErrors | ForEach-Object { Write-Host "路径$($_.Path):$($_.Message)" }
    exit 1
}

内容的提问来源于stack exchange,提问作者Jay Really

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 12:06:03