{"id":19280161,"url":"https://github.com/ocaml-ppx/ppx_deriving_yojson","last_synced_at":"2025-04-04T20:14:58.997Z","repository":{"id":20449530,"uuid":"23726587","full_name":"ocaml-ppx/ppx_deriving_yojson","owner":"ocaml-ppx","description":"A Yojson codec generator for OCaml.","archived":false,"fork":false,"pushed_at":"2025-03-21T15:51:59.000Z","size":373,"stargazers_count":157,"open_issues_count":30,"forks_count":47,"subscribers_count":8,"default_branch":"master","last_synced_at":"2025-03-29T05:45:55.645Z","etag":null,"topics":["deriving","json"],"latest_commit_sha":null,"homepage":"","language":"OCaml","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ocaml-ppx.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2014-09-06T04:25:31.000Z","updated_at":"2025-03-21T15:50:17.000Z","dependencies_parsed_at":"2024-06-17T05:29:51.892Z","dependency_job_id":"d96c8d44-46de-4b2a-98e8-7ac34e29f9ff","html_url":"https://github.com/ocaml-ppx/ppx_deriving_yojson","commit_stats":null,"previous_names":["whitequark/ppx_deriving_yojson"],"tags_count":21,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ocaml-ppx%2Fppx_deriving_yojson","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ocaml-ppx%2Fppx_deriving_yojson/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ocaml-ppx%2Fppx_deriving_yojson/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ocaml-ppx%2Fppx_deriving_yojson/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ocaml-ppx","download_url":"https://codeload.github.com/ocaml-ppx/ppx_deriving_yojson/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247242681,"owners_count":20907134,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["deriving","json"],"created_at":"2024-11-09T21:17:07.453Z","updated_at":"2025-04-04T20:14:58.975Z","avatar_url":"https://github.com/ocaml-ppx.png","language":"OCaml","funding_links":[],"categories":[],"sub_categories":[],"readme":"[@@deriving yojson]\n===================\n\n_deriving Yojson_ is a [ppx_deriving][pd] plugin that generates\n[JSON][] serializers and deserializes that use the [Yojson][] library\nfrom an OCaml type definition.\n\nSponsored by [Evil Martians](http://evilmartians.com).\n\n[pd]: https://github.com/ocaml-ppx/ppx_deriving\n[json]: http://tools.ietf.org/html/rfc4627\n[yojson]: https://github.com/ocaml-community/yojson\n\nNote: [ppx_yojson_conv](https://github.com/janestreet/ppx_yojson_conv) is a more recent deriving extension for Yojson that uses a more durable technical foundation and is more actively maintained.\nWe keep maintaing `ppx_deriving_yojson` for our existing users, but we would recommend that *new projects* start from `ppx_yojson_conv` instead.\n\nInstallation\n------------\n\n_deriving Yojson_ can be installed via [OPAM](https://opam.ocaml.org):\n\n    $ opam install ppx_deriving_yojson\n\nUsage\n-----\n\nIn order to use _deriving yojson_, require the package `ppx_deriving_yojson`.\n\nIf you are using dune, add `ppx_deriving_json` to the `preprocess` entry, and `ppx_deriving_json.runtime` to your requirements, like so:\n\n```\n...\n(libraries  yojson core ppx_deriving_yojson.runtime)\n(preprocess (pps ppx_deriving_yojson))\n...\n```\n\nSyntax\n------\n\n_deriving yojson_ generates two functions per type:\n\n``` ocaml\n# #require \"ppx_deriving_yojson\";;\n# type ty = .. [@@deriving yojson];;\nval ty_of_yojson : Yojson.Safe.t -\u003e (ty, string) Result.result\nval ty_to_yojson : ty -\u003e Yojson.Safe.t\n```\n\nWhen the deserializing function returns \u003ccode\u003eError loc\u003c/code\u003e, `loc` points to the point in the JSON hierarchy where the error has occurred.\n\nIt 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.\n\nIf the type is called `t`, the functions generated are `{of,to}_yojson` instead of `t_{of,to}_yojson`.\n\nUsing the option `[@@deriving yojson { exn = true }]` will also generate a function `ty_of_yojson_exn : Yojson.Safe.t -\u003e ty` which raises `Failure err` on error instead of returning an `Error err` result.\n\nSemantics\n---------\n\n_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.\n\nThe following table summarizes the correspondence between OCaml types and JSON values:\n\n| OCaml type             | JSON value | Remarks                          |\n| ---------------------- | ---------- | -------------------------------- |\n| `int`, `int32`, `float`| Number     |                                  |\n| `int64`, `nativeint`   | Number     | Can exceed range of `double`     |\n| `bool`                 | Boolean    |                                  |\n| `string`, `bytes`      | String     |                                  |\n| `char`                 | String     | Strictly one character in length |\n| `list`, `array`        | Array      |                                  |\n| A tuple                | Array      |                                  |\n| `ref`                  | 'a         |                                  |\n| `option`               | Null or 'a |                                  |\n| A record               | Object     |                                  |\n| `Yojson.Safe.t`        | any        | Identity transformation          |\n| `unit`                 | Null       |                                  |\n\nVariants (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:\n\n``` ocaml\n# type pvs = [ `A | `B of int | `C of int * string ] list [@@deriving yojson];;\n# type v = A | B of int | C of int * string [@@deriving yojson];;\n# type vs = v list [@@deriving yojson];;\n# print_endline (Yojson.Safe.to_string (vs_to_yojson [A; B 42; C (42, \"foo\")]));;\n[[\"A\"],[\"B\",42],[\"C\",42,\"foo\"]]\n# print_endline (Yojson.Safe.to_string (pvs_to_yojson [`A; `B 42; `C (42, \"foo\")]));;\n[[\"A\"],[\"B\",42],[\"C\",42,\"foo\"]]\n```\n\nRecord variants are represented in the same way as if the nested structure was defined separately. For example:\n\n```ocaml\n# type v = X of { v: int } [@@deriving yojson];;\n# print_endline (Yojson.Safe.to_string (v_to_yojson (X { v = 0 })));;\n[\"X\",{\"v\":0}]\n```\n\nRecord variants are currently not supported for extensible variant types.\n\nBy 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.\n\n### Options\n\nOption attribute names may be prefixed with `yojson.` to avoid conflicts with other derivers.\n\n#### [@key]\n\nIf the JSON object keys differ from OCaml conventions, lexical or otherwise, it is possible to specify the corresponding JSON key implicitly using \u003ccode\u003e[@key \"field\"]\u003c/code\u003e, e.g.:\n\n``` ocaml\ntype geo = {\n  lat : float [@key \"Latitude\"];\n  lon : float [@key \"Longitude\"];\n}\n[@@deriving yojson]\n```\n\n#### [@name]\n\nIf the JSON variant names differ from OCaml conventions, it is possible to specify the corresponding JSON string explicitly using \u003ccode\u003e[@name \"constr\"]\u003c/code\u003e, e.g.:\n\n``` ocaml\ntype units =\n| Metric   [@name \"metric\"]\n| Imperial [@name \"imperial\"]\n[@@deriving yojson]\n```\n\n#### [@encoding]\n\nVery 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 \u003ccode\u003e[@encoding \\`string]\u003c/code\u003e attribute to encode them as strings.\n\n#### [@default]\n\nIt is possible to specify a default value for fields that can be missing from the JSON object, e.g.:\n\n``` ocaml\ntype pagination = {\n  pages   : int;\n  current : (int [@default 0]);\n} [@@deriving yojson]\n```\n\nFields with default values are not required to be present in inputs and will not be emitted in outputs.\n\n#### [@to_yojson] / [@of_yojson]\n\nOne can provide custom serialization or deserialization functions, either\noverriding the default derivation or to provide support for abstract, functor,\nor other types that aren't otherwise amenable to derivation (similar to the\n`@printer` option provided by [ppx_deriving's `show` plugin](https://github.com/ocaml-ppx/ppx_deriving#plugin-show)):\n\n```ocaml\n# module StringMap = Map.Make(struct type t = string let compare = compare end);;\n# let yojson_of_stringmap m = StringMap.bindings m\n                           |\u003e [%to_yojson: (string * string) list];;\n# type page = { number : int [@to_yojson fun i -\u003e `Int (i + 1)]\n              ; bounds : (int * int * int * int)\n              ; attrs  : string StringMap.t [@to_yojson yojson_of_stringmap]}\n              [@@deriving to_yojson];;\n# { number = 0\n  ; bounds = (0, 0, 792, 612)\n  ; attrs  = StringMap.add \"foo\" \"bar\" StringMap.empty }\n  |\u003e page_to_yojson\n  |\u003e Yojson.Safe.to_string\n  |\u003e print_endline\n\n{\"number\":1,\"bounds\":[0,0,792,612],\"attrs\":[[\"foo\",\"bar\"]]}\n```\n\n#### `Yojson_meta` module\n\nThe `meta` deriver option can be used to generate a module containing all JSON key names, e.g.\n\n```ocaml\ntype foo = {\n fvalue : float;\n svalue : string [@key \"@svalue_json\"];\n ivalue : int;\n} [@@deriving to_yojson { strict = false; meta = true } ]\nend\n```\n\ndefines the following module:\n\n```ocaml\nmodule Yojson_meta_foo = struct\n  let keys = [\"fvalue\"; \"@svalue_json\"; \"ivalue\"]\n  let _ = keys\nend\n```\n\nWhen the type is named `t`, the module is named just `Yojson_meta`.\n\nLicense\n-------\n\n_deriving yojson_ is distributed under the terms of [MIT license](LICENSE.txt).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Focaml-ppx%2Fppx_deriving_yojson","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Focaml-ppx%2Fppx_deriving_yojson","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Focaml-ppx%2Fppx_deriving_yojson/lists"}