Created
March 16, 2026 12:25
-
-
Save einarwh/e68547ddbd0557eaf8c8d4738453a90a to your computer and use it in GitHub Desktop.
Tagging JSON with schema.
This file contains hidden or 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
| let toValidatedJson (schemaText: string) (schemaName: string) (o: obj) = | |
| let jsonDoc = JsonSerializer.SerializeToDocument(o, serializerOptions) | |
| let schema = JsonSchema.FromText(schemaText) | |
| let evalOptions = EvaluationOptions() | |
| evalOptions.OutputFormat <- OutputFormat.Flag | |
| evalOptions.RequireFormatValidation <- true | |
| let results = schema.Evaluate(jsonDoc.RootElement, evalOptions) | |
| if results.IsValid then | |
| let jsonObj = JsonObject.Create(jsonDoc.RootElement) | |
| let validatorName = | |
| let assembly = Assembly.GetAssembly(typedefof<JsonSchema>) | |
| let assemblyName = assembly.GetName().Name | |
| let versionAttribute = assembly.GetCustomAttribute<AssemblyFileVersionAttribute>() | |
| let versionNumber = if versionAttribute = null then "?" else versionAttribute.Version | |
| $"{assemblyName}-{versionNumber}" | |
| jsonObj.Add("$schema", schemaName) | |
| jsonObj.Add("$validator", validatorName) | |
| jsonObj.ToJsonString() | |
| else | |
| raise <| Exception $"The serialized JSON is not valid according to schema {schemaName}." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment