Yojson and ppx_deriving_yojson

code :

open Yojson

(* Define an OCaml type *)
type person = {
  name : string;
  age : int;
  } 
[@@deriving to_yojson]

(* Example person *)
let my_person = { name = "Alice"; age = 30 }
(* let xx = person_to_yojson my_person *)

(* Convert person to JSON and store in a file *)
let store_person_as_json_file filename person =
  let json_str = Yojson.Safe.to_string (person_to_yojson person) in
  let oc = open_out filename in
  output_string oc json_str;
  close_out oc

(* Usage *)
let () = store_person_as_json_file "person.json" my_person

while executing this I am getting error

dune build
File "bin/main.ml", line 36, characters 40-56:
36 |   let json_str = Yojson.Safe.to_string (person_to_yojson person) in
                                             ^^^^^^^^^^^^^^^^
Error: Unbound value person_to_yojson

dune file

(executable
 (public_name cst_viewer)
 (name main)
 (libraries cst_viewer syntax yojson ppx_deriving_yojson))

(dirs syntax ml js_parser ext)

(env
 (dev
  (env-vars
   (CPPO_FLAGS -U=RELEASE)))
 (release
  (env-vars
   (CPPO_FLAGS -D=RELEASE))
  (ocamlopt_flags
   (:standard -O3 -unbox-closures)))
 (static
  (env-vars
   (CPPO_FLAGS -D=RELEASE))
  (ocamlopt_flags
   (:standard -O3 -unbox-closures))))

AIM : wanted to convert the custom type of ocaml to json. please let me know if I am doing anything wrong or if there’s any other way to convert OCaml custom types to Json?

You should also have a preprocess directive to invoke the pre-processor. Something like (preprocess (pps ppx_deriving_yojson)) in the executable stanza (e.g. just after libraries).

Also, note that if the type you want to print is not defined by you but by some other library and the library itself does not provide the to_json function, you might need to
vendor the code and modify it.

Actually, there is a trick to derive from types defined in other modules: GitHub - ocaml-ppx/ppx_deriving: Type-driven code generation for OCaml

2 Likes

Neat. But if the type is too complex or abstract, this won’t work too well. Since in another thread @ashu414 mentioned rescripts Parsetree (which I’m assuming is full of mutually recursive definitions) I wanted to warn in advance that it may be hard to achieve what they want.

Yeah, I agree with you.

In addition to what @K_N said, also remove ppx_deriving_yojson from the (libraries) list. I think that Dune should warn about that (a ppx rewriter is not something you link against).

Thanks @K_N it’s working now

@emillon @K_N Facing one more issue, can you please help me
Issue Thread : Not able to use %{d}_to_yojson in different path