summaryrefslogtreecommitdiff
path: root/lib/configuration/json5.ml
blob: f6e182cc3c19065ab955b81867e7cf936ae0164f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
module Json_decodeable :
  Decoders.Decode.Decodeable with type value = Yojson_five.Basic.t = struct
  type value = Yojson_five.Basic.t

  let pp fmt json = Yojson.Basic.pretty_print fmt json

  let of_string : string -> (value, string) result =
   fun string -> Yojson_five.Basic.from_string string

  let of_file file = Yojson_five.Basic.from_file file
  let get_string = function `String value -> Some value | _ -> None
  let get_int = function `Int value -> Some value | _ -> None

  let get_float = function
    | `Float value -> Some value
    | `Int value -> Some (float_of_int value)
    | _ -> None

  let get_bool = function `Bool value -> Some value | _ -> None
  let get_null = function `Null -> Some () | _ -> None

  let get_list : value -> value list option = function
    | `List l -> Some l
    | _ -> None

  let get_key_value_pairs : value -> (value * value) list option = function
    | `Assoc assoc ->
        Some (List.map (fun (key, value) -> (`String key, value)) assoc)
    | _ -> None

  let to_list values = `List values
end

module Decode = Decoders.Decode.Make (Json_decodeable)

module Json_encodeable = struct
  type value = Yojson_five.Basic.t

  let to_string json = Yojson_five.Basic.to_string json
  let of_string x = `String x
  let of_int x = `Int x
  let of_float x = `Float x
  let of_bool x = `Bool x
  let null = `Null
  let of_list xs = `List xs

  let of_key_value_pairs xs =
    `Assoc
      (xs
      |> Decoders.Util.My_list.filter_map (fun (k, v) ->
          match k with `String k -> Some (k, v) | _ -> None))
end

module Encode = Decoders.Encode.Make (Json_encodeable)