如何解决OCaml:如何使用 Yojson 派生 JSON 记录,其中字段名称之一是 OCaml 关键字?
我正在尝试制作一个 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]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。