使用 hl_yaml 反序列化 YAML 資料

任務

資料格式 / YAML / 反序列化 YAML 資料

反序列化一個 YAML 檔案,其結構映射到某些 OCaml 類型。

使用的 Opam 套件

  • hl_yaml 測試版本: 1.0.0 — 使用的函式庫: hl_yaml
  • ppx_deriving_yojson 測試版本: 3.7.0 — 使用的函式庫: ppx_deriving_yojson

程式碼

這是我們要反序列化成下方定義的類型的字串。

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_yojson] 屬性使函式庫 ppx_deriving_yojson 中的 ppx 產生函式 ingredient_of_yojson : Yojson.Safe.t -> (ingredient, string) result。如果需要序列化和反序列化,請將 of_yojson 替換為 yojson

type ingredient = {
  name: string;
  weight: int;
} [@@deriving of_yojson]

這裡產生的函式 recipe_of_yojson : Yojson.Safe.t -> (ingredient, string) result 在內部使用 ingredient_of_yojson

type recipe = {
  name: string; [@key "french name"]
  ingredients: ingredient list;
  steps: string list;
} [@@deriving of_yojson]

parse 接受一個將 Yojson.Safe.t 轉換為所需記錄類型的函式作為參數。

let pate_sucree =
  yaml
  |> Hl_yaml.Unix.parse ~of_yojson:recipe_of_yojson

食譜無法運作?註解不清楚或過時?

開啟議題貢獻此食譜

此任務的其他食譜