问题描述
我正在尝试制作一个 visjs-network 库可以接受的 json。
https://visjs.github.io/vis-network/docs/network/
为此,我需要创建一个节点和边数组。 虽然每个节点都包含名称可以安全用作 OCaml 中记录字段的字段(id、标签等),但边需要名称为“to”的字段。不幸的是,这是 OCaml 中的关键字,因此我无法将其作为记录名称。
我正在使用 ppx_yojson_conv
将 OCaml 记录转换为 yojson
对象。
https://github.com/janestreet/ppx_yojson_conv https://github.com/ocaml-community/yojson
这是一些代码:
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]
我能否以某种方式创建一个可以被 yojson
库轻松解析而无需手动转换每个字段的 OCaml 类型?
解决方法
您可以在字段级别添加 [@key "your_arbitrary_name"]
:
type edge = {
from: int;
to_: int [@key "to"];
arrow: string
} [@@deriving yojson_of]