zajer
zajer

Reputation: 803

OCaml: How to derive a JSON record using Yojson where one of the field names is an OCaml keyword?

I am trying to make a json that will be acceptable by visjs-network library.

https://visjs.github.io/vis-network/docs/network/

To do so I need to create an array of nodes and edges. While each node consists of fields that names are safe to use as records' fields in OCaml (id,label etc) edges require field with name "to". Unfortunately this is a keyword in OCaml so I can't make it a name of a record.

I am using ppx_yojson_conv for converting OCaml records into yojson objects.

https://github.com/janestreet/ppx_yojson_conv https://github.com/ocaml-community/yojson

Here is some code:

type node = {id:int;label:string;shape:string;color:string} (* this type is perfectly ok since it is exactly what visjs library accepts and OCaml accepts each of its fields' name *)
[@@deriving yojson_of]
type edge = {from:int;to:int;arrow:string} (* this type is what visjs accepts but OCaml does not allow to create field with the name "to" *)
[@@deriving yojson_of]

Can I somehow create an OCaml type that will be easily parsable by yojson library without manual conversion of each field ?

Upvotes: 1

Views: 627

Answers (1)

X. Van de Woestyne
X. Van de Woestyne

Reputation: 637

you can add the [@key "your_arbitrary_name"] at the field level:

type edge = {
   from: int;
   to_: int [@key "to"];
   arrow: string
} [@@deriving yojson_of]

As mentionned here: https://github.com/janestreet/ppx_yojson_conv#records

Upvotes: 1

Related Questions