Serialise JSON Data using ppx_yojson_conv
Task
Data Formats / JSON / Serialise JSON Data
Opam Packages Used
- ppx_yojson_conv Tested with version: v0.17.0 — Used libraries: ppx_yojson_conv
- yojson Tested with version: 3.0.0 — Used libraries: yojson
Code
Ppx_yojson_conv_lib.Yojson_conv.Primitives contains functions needed to serialise values of primitive types.
open Ppx_yojson_conv_lib.Yojson_conv.Primitives
The annotation [@@deriving yojson] causes the PPX from ppx_yojson_conv to generate a function
yojson_of_language that converts values from type language to Yojson.Safe.t.
type language = {
name: string;
url: string
} [@@deriving yojson]
let ocaml_language = {
name = "ocaml";
url= "https://ocaml.org/"
}
We convert the value ocaml_language to a Yojson.Safe.t, using the function yojson_of_language generated by the PPX,
and then convert that to a string.
let () =
ocaml_language
|> yojson_of_language
|> Yojson.Safe.to_string
|> print_endline