Last active
July 1, 2021 15:38
-
-
Save JamesNK/7e6d026c8b78c049bb1e1b6fb0ed85cf to your computer and use it in GitHub Desktop.
Validate Schema from PowerShell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ErrorActionPreference = "Stop" | |
$NewtonsoftJsonPath = Resolve-Path -Path "bin\Newtonsoft.Json.dll" | |
$NewtonsoftJsonSchemaPath = Resolve-Path -Path "bin\Newtonsoft.Json.Schema.dll" | |
Add-Type -Path $NewtonsoftJsonPath | |
Add-Type -Path $NewtonsoftJsonSchemaPath | |
$source = @' | |
public class Validator | |
{ | |
public static System.Collections.Generic.IList<string> Validate(Newtonsoft.Json.Linq.JToken token, Newtonsoft.Json.Schema.JSchema schema) | |
{ | |
System.Collections.Generic.IList<string> messages; | |
Newtonsoft.Json.Schema.SchemaExtensions.IsValid(token, schema, out messages); | |
return messages; | |
} | |
} | |
'@ | |
Add-Type -TypeDefinition $source -ReferencedAssemblies $NewtonsoftJsonPath,$NewtonsoftJsonSchemaPath | |
$Json = @' | |
{"prop1":"value"} | |
'@ | |
$SchemaJson = @' | |
{"type":"array"} | |
'@ | |
write-host "=========================" -foregroundcolor "white" | |
write-host "Json.NET Schema Validator" -foregroundcolor "white" | |
write-host "=========================" -foregroundcolor "white" | |
write-host | |
write-host "Json: $Json" | |
write-host "SchemaJson: $SchemaJson" | |
$Token = [Newtonsoft.Json.Linq.JToken]::Parse($Json) | |
$Schema = [Newtonsoft.Json.Schema.JSchema]::Parse($SchemaJson) | |
$ErrorMessages = [Validator]::Validate($Token, $Schema) | |
$IsValid = $ErrorMessages.Count -eq 0 | |
write-host "Schema is valid: $IsValid" -foregroundcolor "white" | |
foreach ($ErrorMessage in $ErrorMessages) { | |
write-host $ErrorMessage -foregroundcolor "red" | |
} | |
write-host |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
After playing with it a bit, I got this to work in vscode:
Leaving the json and schema as strings resolved the type mismatch errors