Skip to content

Instantly share code, notes, and snippets.

@einarwh
Created March 16, 2026 12:25
Show Gist options
  • Select an option

  • Save einarwh/e68547ddbd0557eaf8c8d4738453a90a to your computer and use it in GitHub Desktop.

Select an option

Save einarwh/e68547ddbd0557eaf8c8d4738453a90a to your computer and use it in GitHub Desktop.
Tagging JSON with schema.
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