Ocaml Yaml Extracting Value using a Key

Hi Phage. As far as I know, ocaml-yaml doesn’t come with any built-in functionality for extracting values from the Yaml.value type, so you have to do this yourself because the structure of whatever you read in is very dependent on your data.

So for this example you could write a small find function which works for the `O of (string * value) list type (see here for those types).

Simplest Solution

let find key (yaml : Yaml.value) = match yaml with 
  | `O assoc -> List.assoc_opt key assoc
  | _ -> None

Here we pattern-match to extract the Yaml.value we want (anything else returns None) and use the standard library’s assoc_opt to looks for the correct entry in our “association list”. This function returns a Yaml.value option.

Here is an example usage of that function:

let () = 
  let yaml = Yaml_unix.of_file_exn (Fpath.v "testyaml.yml") in 
    match find "api" yaml with 
      | Some yaml_value -> Yaml.pp Format.std_formatter yaml_value
      | None -> print_endline "Didn't find anything :/"

All going well this should print 222 to standard output. Hope this helps.

Experimental Solution

I’m using ocaml-yaml quite a lot and I’m making a ppx that transforms OCaml types to YAML types (and back again). Note this is very much a WIP, but I’m more than happy to fix any bugs or help with you using it if you wish to do so :).

This means if you know the structure of your YAML ahead of time you can describe it using OCaml types and let the ppx generate functions to transform it. The example above would become:

type t = {api: int; secret: string} [@@deriving yaml]

let () = 
  let yaml = Yaml_unix.of_file_exn (Fpath.v "testyaml.yml") in 
    match of_yaml yaml with 
      | Ok v -> print_int v.api
      | Error (`Msg m) -> failwith m 
4 Likes