[ANN] first release of ppx_deriving_jsonschema

It is my pleasure to announce the first release of ppx_deriving_jsonschema. Source repo is GitHub - ahrefs/ppx_deriving_jsonschema

This small ppx should help you generate a (hopefully valid) json schema from an ocaml type.

Generally the derivation tries to produce a schema which looks natural, and that would also be compatible with the existing derivers for json out there. Basically you should be able to change the annotation to [@@deriving jsonschema, yojson] (or json instead of yojson) and to read/write json values that are matching the schema. There is a bit of tension on things like variants, which are represented as arrays by ppx_yojson_conv and ppx_deriving_yojson, but represented as enums by ppx_deriving_jsonschema. I plan to add a way to switch between the two behaviors soon.

type address = {
  street: string;
  city: string;
  zip: string;
} [@@deriving jsonschema]

type t = {
  name: string;
  age: int;
  email: string option;
  address: address;
} [@@deriving jsonschema]

let schema = Ppx_deriving_jsonschema_runtime.json_schema t_jsonschema

Will be turned into this schema

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "address": {
      "type": "object",
      "properties": {
        "zip": { "type": "string" },
        "city": { "type": "string" },
        "street": { "type": "string" }
      },
      "required": [ "zip", "city", "street" ]
    },
    "email": { "type": "string" },
    "age": { "type": "integer" },
    "name": { "type": "string" }
  },
  "required": [ "address", "age", "name" ]
}

Some more advanced functionalities are documented in the readme.

Please let me know if you see any important feature missing, if there are bugs, or if you have ideas of improvements.

This project was originally started during a Ahrefs dojo, in parallel to the ICFP conference in Milan, as a way to learn how to write a ppx. I can’t recommend enough GitHub - pedrobslisboa/ppx-by-example: This repository contains examples to help on understanding what are and how to write PPXs in OCaml. to get going.

14 Likes

Released 0.0.2 on opam. It feels like the project is in a good shape now.

Changes:

  • support for nativeint, bytes, ref, unit
  • add ~variant_as_array for compatibility with ppx_deriving_yojson
  • support variant payloads
  • support polymorphic variants inheritance
  • fix encoding of tuples
  • change encoding of variants from enum to anyOf

I’m considering making variant_as_array the default in 0.0.3 as it would be more consistent with the ocaml ecosystem.

3 Likes