使用 yaml 反序列化 YAML 資料
任務
資料格式 / YAML / 反序列化 YAML 資料
反序列化一個 YAML 檔案,其結構映射到某些 OCaml 類型。
使用的 Opam 套件
- yaml 測試版本:3.2.0 — 使用的函式庫:yaml
- ppx_deriving_yaml 測試版本:0.2.2 — 使用的函式庫:ppx_deriving_yaml
程式碼
這是我們將反序列化為下面定義的類型的字串。
let yaml = {|
french name: pâte sucrée
ingredients:
- name: flour
weight: 250
- name: butter
weight: 100
- name: sugar
weight: 100
- name: egg
weight: 50
- name: salt
weight: 5
steps:
- soften butter
- add sugar
- add egg and salt
- add flour
|}
[@@deriving of_yaml]
屬性使得來自函式庫 ppx_deriving_yaml
的 ppx 生成函數 ingredient_of_yaml : Yaml.value -> (ingredient, [> `Msg of string]) result
。 如果需要序列化和反序列化,請將 of_yaml
替換為 yaml
。
type ingredient = {
name: string;
weight: int;
} [@@deriving of_yaml]
這裡生成的函數 recipe_of_yaml : Yaml.value -> (ingredient, [> `Msg of string]) result
在內部使用 ingredient_of_yaml
。
type recipe = {
name: string; [@key "french name"]
ingredients: ingredient list;
steps: string list;
} [@@deriving of_yaml]
解析並轉換為記錄是串接在一起的。
let pate_sucree =
yaml
|> Yaml.of_string
|> fun yaml -> Result.bind yaml recipe_of_yaml