janestreet / ppx_yojson_conv

[@@deriving] plugin to generate Yojson conversion functions
MIT License
58 stars 8 forks source link

[@yojson.option] not work in string->record #3

Closed impvd closed 3 years ago

impvd commented 3 years ago

As it mentioned in the README

type t =
  { x : int option;
    y : int option [@yojson.option];
  } [@@deriving yojson]

Would match the following examples:

{ x = Some 1; y = Some 2; } => {"x":1,"y":2}
{ x = None  ; y = None;   } => {"x":null}

I would like to make it reverse as follows:

let short_case_null = {|
  {
    "id": 11304240,
    "transform": null
  }
|}

let short_case_ident =
  {|
  {
    "id": 11304240,
    "transform": "ident"
  }
|}

type quandl_gld_dataset = {
  id : int; [@key "id"]
  transform : string option; [@key "transform"]
}
[@@deriving yojson]

let null_json =
  quandl_gld_dataset_of_yojson (Yojson.Safe.from_string short_case_null)

let ident_json =
  quandl_gld_dataset_of_yojson (Yojson.Safe.from_string short_case_ident)

let () =
  match null_json.transform with
  | Some trans -> print_endline trans
  | None -> prerr_endline "null"

let () =
  match ident_json.transform with
  | Some trans -> print_endline trans
  | None -> prerr_endline "null"

Basically it works well in this case, however when I tried to change it from transform : string option; [@key "transform"] to transform : string option; [@key "transform"] [@yojson.option] , there's an error:

Fatal error: exception Ppx_yojson_conv_lib__Yojson_conv.Of_yojson_error(_, 870828711)

Just curios if it is not necessary to use [@yojson.option] in this case?

hhugo commented 3 years ago

To get the semantic you want, you can use transform : string option [@key "transform"] [@yojson.default None].

Using [@yojson.option] modifies the behavior of option. It means

hhugo commented 3 years ago

Comment back here if you think your issue is not fully addressed.