janestreet / ppx_yojson_conv

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

Deriving converters for `Yojson.Safe.t` #7

Open psteckler opened 3 years ago

psteckler commented 3 years ago

I have a type that contains a use of Yojson.Safe.t, like:

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

In my editor using Merlin, Yojson.Safe.t is highlighted red, indicating there's no Yojson.Safe.t_of_yojson (which would be the identity function).

I'm using ppx_yojson_conv v0.13.0 with OCaml 4.11.2.

Is this a known issue? Is there a workaround?

Incidentally, ppx_deriving_yojson has no trouble with this code.

kwohlfahrt commented 3 years ago

I found the following worked for me, but I'm new to OCaml so there might be other issues with it:

module Safe = struct
  include Yojson.Safe

  let t_of_yojson x = x
  let yojson_of_t = x
end

type foo = {
  xs : Safe.t;
}[@@deriving yojson];;
zbaylin commented 2 years ago

You can also do this using generic types, i.e.

type 'a t_ = {
  x : 'a;
  y : int
}
[@@deriving yojson_of]

type t = Yojson.Safe.t t_

let yojson_of_t = yojson_of_t_ Fun.id

although this is somewhat verbose

zoj613 commented 3 months ago

Is there any support for this yet? I'd like to have a record field be any valid json object. I thought using Yojson.Safe.t would work but it raises the same error as OP.