Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: allow_extra_fields #42

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 43 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,9 +177,9 @@ The PPX is included in the `melange-json` package. To use it, just add the

### Usage

To generate JSON converters for a type,
add the `[@@deriving json]` attribute to the type declaration,
ensuring the converters for primitives like `int` and `string` are in scope if necessary:
To generate JSON converters for a type, add the `[@@deriving json]` attribute to
the type declaration, ensuring the converters for primitives like `int` and
`string` are in scope if necessary:

```ocaml
open Ppx_deriving_json_runtime.Primitives
Expand Down Expand Up @@ -221,6 +221,46 @@ let t = of_json (Json.parseOrRaise {|{"a": 42}|})
(* t = { a = 42; b = "-"; } *)
```

#### `[@json.allow_extra_fields]` on records

Sometimes, the JSON objects might contain keys that are not part of the OCaml
type definition. The `[@json.allow_extra_fields]` attribute allows you to
gracefully ignore such additional fields instead of raising an error during
deserialization.

This attribute can be used on records, even when they are embedded in other
types.

**Example 1: Ignoring extra fields in records**

```ocaml
type allow_extra_fields = {
a: int;
} [@@deriving json] [@@json.allow_extra_fields]

let t = allow_extra_fields_of_json (Json.parseOrRaise {|{"a": 42, "extra": "ignore me"}|})
(* t = { a = 42 } *)
```

The additional key `"extra"` in the JSON input is ignored, and the record is
successfully deserialized.

**Example 2: Ignoring extra fields in inline records**

```ocaml
type allow_extra_fields2 =
| A of { a: int } [@json.allow_extra_fields]
[@@deriving json]

let t = allow_extra_fields2_of_json (Json.parseOrRaise {|{"tag": "A", "a": 42, "extra": "ignore me"}|})
(* t = A { a = 42 } *)
```

In this case, the `[@json.allow_extra_fields]` attribute is applied directly to
the inline record in the variant constructor. This allows the variant to ignore
extra fields in the JSON payload while properly deserializing the fields that
match the type definition.

#### `[@json.option]`: a shortcut for `[@json.default None]`

When a field has type `_ option` then you can use the `[@json.option]` attribute
Expand Down