@@ -175,9 +175,9 @@ The PPX is included in the `melange-json` package. To use it, just add the
175175
176176### Usage
177177
178- To generate JSON converters for a type,
179- add the ` [@@deriving json] ` attribute to the type declaration,
180- ensuring the converters for primitives like ` int ` and ` string ` are in scope if necessary:
178+ To generate JSON converters for a type, add the ` [@@deriving json] ` attribute to
179+ the type declaration, ensuring the converters for primitives like ` int ` and
180+ ` string ` are in scope if necessary:
181181
182182``` ocaml
183183open Melange_json.Primitives
@@ -219,6 +219,51 @@ let t = of_json (Melange_json.of_string {|{"a": 42}|})
219219(* t = { a = 42; b = "-"; } *)
220220```
221221
222+ #### ` [@json.allow_extra_fields] ` on records
223+
224+ Sometimes, the JSON objects might contain keys that are not part of the OCaml
225+ type definition. The ` [@json.allow_extra_fields] ` attribute allows you to
226+ gracefully ignore such additional fields instead of raising an error during
227+ deserialization.
228+
229+ This attribute can be used on records, even when they are embedded in other
230+ types.
231+
232+ > ** Note:** For the Melange PPX, ignoring extra fields is the default behavior -
233+ > you don't need to explicitly add the ` [@json.allow_extra_fields] ` attribute.
234+ > The attribute is primarily useful for the native PPX where strict field
235+ > checking is the default.
236+
237+ ** Example 1: Ignoring extra fields in records**
238+
239+ ``` ocaml
240+ type allow_extra_fields = {
241+ a: int;
242+ } [@@deriving json] [@@json.allow_extra_fields]
243+
244+ let t = allow_extra_fields_of_json (Json.parseOrRaise {|{"a": 42, "extra": "ignore me"}|})
245+ (* t = { a = 42 } *)
246+ ```
247+
248+ The additional key ` "extra" ` in the JSON input is ignored, and the record is
249+ successfully deserialized.
250+
251+ ** Example 2: Ignoring extra fields in inline records**
252+
253+ ``` ocaml
254+ type allow_extra_fields2 =
255+ | A of { a: int } [@json.allow_extra_fields]
256+ [@@deriving json]
257+
258+ let t = allow_extra_fields2_of_json (Json.parseOrRaise {|{"tag": "A", "a": 42, "extra": "ignore me"}|})
259+ (* t = A { a = 42 } *)
260+ ```
261+
262+ In this case, the ` [@json.allow_extra_fields] ` attribute is applied directly to
263+ the inline record in the variant constructor. This allows the variant to ignore
264+ extra fields in the JSON payload while properly deserializing the fields that
265+ match the type definition.
266+
222267#### ` [@json.option] ` : a shortcut for ` [@json.default None] `
223268
224269When a field has type ` _ option ` then you can use the ` [@json.option] ` attribute
0 commit comments