OCaml JSON Schema

A JSON Schema validator for OCaml supporting drafts 4, 6, 7, 2019-09, and 2020-12.

Installation

opam install jsonschema

Usage

High-level API

open Jsonschema

(* Validate JSON string against schema string *)
let schema = {|{"type": "object", "required": ["name"]}|}
let json = {|{"name": "John", "age": 30}|}

match validate_strings ~schema ~json with
| Ok () -> print_endline "Valid!"
| Error err -> print_endline (Validation_error.to_string err)

(* Validate from files *)
let json = Yojson.Basic.from_file "data.json" in
match validate_file ~schema:"schema.json" json with
| Ok () -> print_endline "Valid!"
| Error err -> print_endline (Validation_error.to_string err)

(* Create a reusable validator *)
match create_validator "schema.json" with
| Ok validator ->
    let json = Yojson.Basic.from_file "data.json" in
    (match validate validator json with
     | Ok () -> print_endline "Valid!"
     | Error err -> print_endline (Validation_error.to_string err))
| Error err -> pp_compile_error Format.std_formatter err

JSON Pointer

let json = `Assoc [("foo", `Assoc [("bar", `Int 42)])] in
match Json_pointer.of_string "/foo/bar" with
| Ok ptr ->
    (match Json_pointer.lookup ptr json with
     | Some (`Int n) -> Printf.printf "Found: %d\n" n
     | _ -> print_endline "Not found")
| Error e -> Printf.printf "Invalid pointer: %s\n" e

Format Validators

The library includes validators for common formats:

Implementation Status

Test Coverage by Draft Version

Core Features (Fully Implemented)

Schema Composition (Partially Implemented)

Object Validation (Fully Implemented)

Array Validation (Fully Implemented)

References and Schema Identification

Advanced Validation

Content Validation

Output Formats

Known Limitations

License

ocaml-jsonschema is available under the ISC License.