OCaml By Examples

json

console

yojson.
$ opam install yojson

utop

open Core

let json = '{  }'

let parse_test_vectors filepath =
Here's how you can parse a json string. Yojson also has other methods like `from_file` to directly parse a `.json` file.
  let json = Yojson.Basic.from_file filepath in
  let open Yojson.Basic.Util in
  let name = json |> member "name" |> to_string in 
  let test_vectors = json |> member "test_vectors" |> to_list in
  let json_to_test_vector test_vector = 
    let input = test_vector |> member "input" |> to_list |> filter_string in
    let output = test_vector |> member "output" |> to_string in
    {input; output}
  in
  let test_vectors = List.map test_vectors ~f:json_to_test_vector in
  {name; test_vectors}

let () = 
  let cur_dir = Sys.argv.(0) |> Filename.dirname in 
  let test_vector_file = Filename.concat cur_dir "three_wire.json" in
  let test_vectors = parse_test_vectors test_vector_file in 
  assert (test_vectors.name = "three_wire");
  let check_test_vector test_vector = 
    let digest = Hash_function.Hash.hash_field_elems test_vector.input in 
    assert (digest = test_vector.output)
  in
  List.map test_vectors.test_vectors ~f:check_test_vector
next: bignum