Skip to content

Commit

Permalink
docs: allow_extra_fields
Browse files Browse the repository at this point in the history
  • Loading branch information
jchavarri committed Nov 28, 2024
1 parent 2899658 commit 4dfd38a
Showing 1 changed file with 43 additions and 3 deletions.
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

0 comments on commit 4dfd38a

Please sign in to comment.