package ppx_deriving_yojson

All checked builds pass
  1. Overview
  2. Docs
JSON codec generator for OCaml

Install

dune-project
 Dependency

Authors

Maintainers

Sources

ppx_deriving_yojson-3.10.0.tbz
sha256=ced3d265e4287f1f18b09df6446a24444fad52b2a3054cbcbe0c9494d0e89b3f
sha512=038752a73690dc1b55031c119f57ee27fbee0d51a4a541d2f31ad1baf8b05637396c0b97a7dbfd77db600b689e90a62bfff7ca3fcf74545bd5b32dc3dabff511

Description

ppx_deriving_yojson is a ppx_deriving plugin that provides a JSON codec generator.

Tags

syntax json

Added to opam-repository:

README

[@@deriving yojson]

deriving Yojson is a ppx_deriving plugin that generates JSON serializers and deserializes that use the Yojson library from an OCaml type definition.

Sponsored by Evil Martians.

Note: ppx_yojson_conv is a more recent deriving extension for Yojson that uses a more durable technical foundation and is more actively maintained. We keep maintaing ppx_deriving_yojson for our existing users, but we would recommend that new projects start from ppx_yojson_conv instead.

Installation

deriving Yojson can be installed via OPAM:

$ opam install ppx_deriving_yojson

Usage

In order to use deriving yojson, require the package ppx_deriving_yojson.

If you are using dune, add ppx_deriving_json to the preprocess entry, and ppx_deriving_json.runtime to your requirements, like so:

...
(libraries  yojson core ppx_deriving_yojson.runtime)
(preprocess (pps ppx_deriving_yojson))
...

Syntax

deriving yojson generates two functions per type:

# #require "ppx_deriving_yojson";;
# type ty = .. [@@deriving yojson];;
val ty_of_yojson : Yojson.Safe.t -> (ty, string) Result.result
val ty_to_yojson : ty -> Yojson.Safe.t

When the deserializing function returns Error loc, loc points to the point in the JSON hierarchy where the error has occurred.

It is possible to generate only serializing or deserializing functions by using [@@deriving to_yojson] or [@@deriving of_yojson]. It is also possible to generate an expression for serializing or deserializing a type by using [%to_yojson:] or [%of_yojson:]; non-conflicting versions [%derive.to_yojson:] or [%derive.of_yojson:] are available as well. Custom or overriding serializing or deserializing functions can be provided on a per-field basis via [@to_yojson] and [@of_yojson] attributes.

If the type is called t, the functions generated are {of,to}_yojson instead of t_{of,to}_yojson.

Using the option [@@deriving yojson { exn = true }] will also generate a function ty_of_yojson_exn : Yojson.Safe.t -> ty which raises Failure err on error instead of returning an Error err result.

Semantics

deriving yojson handles tuples, records, normal and polymorphic variants; builtin types: int, int32, int64, nativeint, float, bool, char, string, bytes, ref, list, array, option and their Mod.t aliases.

The following table summarizes the correspondence between OCaml types and JSON values:

OCaml type

JSON value

Remarks

int, int32, float

Number

int64, nativeint

Number

Can exceed range of double

bool

Boolean

string, bytes

String

char

String

Strictly one character in length

list, array

Array

A tuple

Array

ref

'a

option

Null or 'a

A record

Object

Yojson.Safe.t

any

Identity transformation

unit

Null

Variants (regular and polymorphic) are represented using arrays; the first element is a string with the name of the constructor, the rest are the arguments. Note that the implicit tuple in a polymorphic variant is flattened. For example:

# type pvs = [ `A | `B of int | `C of int * string ] list [@@deriving yojson];;
# type v = A | B of int | C of int * string [@@deriving yojson];;
# type vs = v list [@@deriving yojson];;
# print_endline (Yojson.Safe.to_string (vs_to_yojson [A; B 42; C (42, "foo")]));;
[["A"],["B",42],["C",42,"foo"]]
# print_endline (Yojson.Safe.to_string (pvs_to_yojson [`A; `B 42; `C (42, "foo")]));;
[["A"],["B",42],["C",42,"foo"]]

Record variants are represented in the same way as if the nested structure was defined separately. For example:

# type v = X of { v: int } [@@deriving yojson];;
# print_endline (Yojson.Safe.to_string (v_to_yojson (X { v = 0 })));;
["X",{"v":0}]

Record variants are currently not supported for extensible variant types.

By default, objects are deserialized strictly; that is, all keys in the object have to correspond to fields of the record. Passing strict = false as an option to the deriver (i.e. [@@deriving yojson { strict = false }]) changes the behavior to ignore any unknown fields.

Options

Option attribute names may be prefixed with yojson. to avoid conflicts with other derivers.

[@key]

If the JSON object keys differ from OCaml conventions, lexical or otherwise, it is possible to specify the corresponding JSON key implicitly using [@key "field"], e.g.:

type geo = {
  lat : float [@key "Latitude"];
  lon : float [@key "Longitude"];
}
[@@deriving yojson]
[@name]

If the JSON variant names differ from OCaml conventions, it is possible to specify the corresponding JSON string explicitly using [@name "constr"], e.g.:

type units =
| Metric   [@name "metric"]
| Imperial [@name "imperial"]
[@@deriving yojson]
[@encoding]

Very large int64 and nativeint numbers can wrap when decoded in a runtime which represents all numbers using double-precision floating point, e.g. JavaScript and Lua. It is possible to specify the [@encoding `string] attribute to encode them as strings.

[@default]

It is possible to specify a default value for fields that can be missing from the JSON object, e.g.:

type pagination = {
  pages   : int;
  current : (int [@default 0]);
} [@@deriving yojson]

Fields with default values are not required to be present in inputs and will not be emitted in outputs.

[@to_yojson] / [@of_yojson]

One can provide custom serialization or deserialization functions, either overriding the default derivation or to provide support for abstract, functor, or other types that aren't otherwise amenable to derivation (similar to the @printer option provided by ppx_deriving's show plugin):

# module StringMap = Map.Make(struct type t = string let compare = compare end);;
# let yojson_of_stringmap m = StringMap.bindings m
                           |> [%to_yojson: (string * string) list];;
# type page = { number : int [@to_yojson fun i -> `Int (i + 1)]
              ; bounds : (int * int * int * int)
              ; attrs  : string StringMap.t [@to_yojson yojson_of_stringmap]}
              [@@deriving to_yojson];;
# { number = 0
  ; bounds = (0, 0, 792, 612)
  ; attrs  = StringMap.add "foo" "bar" StringMap.empty }
  |> page_to_yojson
  |> Yojson.Safe.to_string
  |> print_endline

{"number":1,"bounds":[0,0,792,612],"attrs":[["foo","bar"]]}
Yojson_meta module

The meta deriver option can be used to generate a module containing all JSON key names, e.g.

type foo = {
 fvalue : float;
 svalue : string [@key "@svalue_json"];
 ivalue : int;
} [@@deriving to_yojson { strict = false; meta = true } ]
end

defines the following module:

module Yojson_meta_foo = struct
  let keys = ["fvalue"; "@svalue_json"; "ivalue"]
  let _ = keys
end

When the type is named t, the module is named just Yojson_meta.

License

deriving yojson is distributed under the terms of MIT license.

Dependencies (5)

  1. ppxlib >= "0.36.0"
  2. ppx_deriving >= "6.1"
  3. yojson >= "1.6.0"
  4. dune >= "1.0"
  5. ocaml >= "4.05.0"

Dev Dependencies (2)

  1. ounit2 with-test
  2. yojson with-test & < "3"

Optional Dependencies

None

Used by (97)

  1. anthropic
  2. archetype
  3. bitflyer
  4. builder-web >= "0.2.0"
  5. cabal
  6. caisar
  7. caisar-xgboost
  8. camels
  9. canary
  10. colibrics
  11. comby
  12. comby-kernel
  13. coq-lsp >= "0.2.0+8.17"
  14. coq-serapi
  15. crs = "0.0.20250914"
  16. current-albatross-deployer
  17. current_docker
  18. current_examples
  19. current_git
  20. current_github
  21. current_gitlab
  22. current_ocluster
  23. current_web
  24. dap
  25. disml
  26. earlybird
  27. easy_logging_yojson
  28. fiat-p256
  29. frama-c >= "25.0"
  30. fred
  31. fsml
  32. fstar
  33. gemini
  34. gmocoin
  35. goblint
  36. goblint-cil >= "1.8.0"
  37. grpc-examples
  38. guardian
  39. hacl_x25519
  40. hardcaml-lua
  41. hl_yaml
  42. i3ipc
  43. index-bench
  44. jhupllib
  45. jsonschema
  46. jupyter < "2.7.9"
  47. karamel
  48. key-parsers < "1.0.0"
  49. kremlin < "transition"
  50. kubecaml
  51. lambda-runtime
  52. links
  53. mcp-kit-ppx
  54. menhir-lsp >= "0.3.3" & < "0.5.0"
  55. menhirformat
  56. miaou-core
  57. mirage-crypto-ec
  58. morbig
  59. mutaml >= "0.4"
  60. nsq
  61. ocaml_db_model
  62. ocaml_pgsql_model
  63. ocluster-api
  64. oframl
  65. ojs-base
  66. ojs_base
  67. opam-check-npm-deps < "4.1.0"
  68. oraft
  69. oui
  70. p4spectec
  71. pa_ppx = "0.15" | >= "0.19"
  72. pds-reachability
  73. pkcs11
  74. pkcs11-driver
  75. playwright
  76. quill < "1.0.0~alpha3"
  77. repr-bench < "0.2.1"
  78. SZXX >= "2.0.0"
  79. safemoney >= "0.2.0"
  80. satyrographos >= "0.0.2.8"
  81. savvy
  82. shakuhachi
  83. sihl < "0.2.0" | >= "0.3.0~rc2"
  84. sihl-core
  85. slacko
  86. slipshow >= "0.7.0"
  87. soteria
  88. starred_ml
  89. stitch
  90. stog_server
  91. styled-ppx
  92. textrazor
  93. vercel
  94. wamp < "1.0"
  95. webauthn
  96. yosqlite >= "0.2"
  97. zeit

Conflicts

None

Build status

Results of building ppx_deriving_yojson with each compiler on check.ci.ocaml.org, run of against opam-repository 8a77e58. All results for this package.

Each result links to its build log. To keep crawlers from overloading the site, build logs require a GitHub sign-in (see ocurrent/opam-health-check). On your first log, GitHub asks you to “Authorize opam-health-check”, the OCurrent app that runs these checks; it sees only your public profile, not your repositories. The sign-in lasts 30 days.

Version OCaml 4.11 OCaml 4.14 OCaml 5.2 OCaml 5.4 OCaml 5.5
3.10.0 (this version) good good good good good
  • good Package successfully built
  • partial One of the dependencies failed to build
  • bad Package failed to build
  • n/a Package is not available in this environment
  • internal Internal failure