package js_of_ocaml

  1. Overview
  2. Docs
Compiler from OCaml bytecode to JavaScript

Install

dune-project
 Dependency

Authors

Maintainers

Sources

js_of_ocaml-6.4.1.tbz
sha256=e59bbffcaefaba3191620556514b7f53bb3249e3f881a070d72724234dffd819
sha512=bb470f316f9c81a3b2b8dedd0b0f18f8e06beb48dd70df1d9f846de90ffab439cab5ef7a93a8166af0998068b06097e8319bc0d9f4f23a7159b0de8b3b515746

doc/ppx-deriving.html

JSON derivation

The js_of_ocaml-ppx_deriving_json package provides a PPX deriver for serializing OCaml values to JSON.

Important: The serialization format follows js_of_ocaml's internal representation. It is designed for communication between a js_of_ocaml program and a server-side OCaml application, not for interacting with third-party APIs.

Installation

opam install js_of_ocaml-ppx_deriving_json

Usage

Add [@@deriving json] to your type definitions:

type person = {
  name : string;
  age : int;
}
[@@deriving json]

(* Serialize to a JSON string *)
let json_str = Deriving_Json.to_string person_json { name = "Alice"; age = 30 }

(* Deserialize from a JSON string *)
let alice = Deriving_Json.from_string person_json json_str

The [@@deriving json] attribute generates:

  • person_to_json : Buffer.t -> person -> unit — write a value to a buffer
  • person_of_json : Deriving_Json_lexer.lexbuf -> person — read a value from a lexer buffer
  • person_json : person Deriving_Json.t — a witness, usable with Deriving_Json.to_string and Deriving_Json.from_string for string conversion (as in the example above)

Note: For types named t, the prefix is omitted (e.g., of_json instead of t_of_json).

The [%to_json: type] and [%of_json: type] syntax also works with any type expression:

let json = [%to_json: int list] [1; 2; 3]
let nums = [%of_json: int list] json

Supported types

The deriver supports:

  • Basic types: int, float, string, bool
  • Options: 'a option
  • Lists and arrays: 'a list, 'a array
  • Records and variants
  • Polymorphic variants
  • Recursive types

See also