OCaml:如何使用 Yojson 派生 JSON 记录,其中字段名称之一是 OCaml 关键字?
OCaml: How to derive a JSON record using Yojson where one of the field names is an OCaml keyword?
我正在尝试制作一个可以被 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]
我能以某种方式创建一个 OCaml 类型吗?yojson
库无需手动转换每个字段即可轻松解析该类型?
您可以在字段级别添加 [@key "your_arbitrary_name"]
:
type edge = {
from: int;
to_: int [@key "to"];
arrow: string
} [@@deriving yojson_of]
我正在尝试制作一个可以被 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]
我能以某种方式创建一个 OCaml 类型吗?yojson
库无需手动转换每个字段即可轻松解析该类型?
您可以在字段级别添加 [@key "your_arbitrary_name"]
:
type edge = {
from: int;
to_: int [@key "to"];
arrow: string
} [@@deriving yojson_of]