package decoders-yojson

  1. Overview
  2. Docs
Yojson backend for decoders

Install

Dune Dependency

Authors

Maintainers

Sources

decoders-1.0.0.tbz
sha256=47fe79c4102d0f710eff3ceaef313100d9df3c7945834d3cf38a39742a573597
sha512=6fe4e9f99d865fb24c8b1da08ba485282fc8eaf6ed48cedbe8109cae863ad441a95b2643b4ea217a6b012f149682ca69af436ed26a3d646903738fce5651a229

doc/src/decoders-yojson/safe.ml.html

Source file safe.ml

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
(** {2 Yojson.Safe implementation} *)

open Decoders

module Json_decodeable : Decode.Decodeable with type value = Yojson.Safe.t =
struct
  type value = Yojson.Safe.t

  let pp fmt json =
    Format.fprintf fmt "@[%s@]" (Yojson.Safe.pretty_to_string json)


  let of_string : string -> (value, string) result =
   fun string ->
    try Ok (Yojson.Safe.from_string string) with
    | Yojson.Json_error msg ->
        Error msg


  let of_file file =
    try Ok (Yojson.Safe.from_file file) with e -> Error (Printexc.to_string e)


  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 = Decode.Make (Json_decodeable)

module Json_encodeable = struct
  type value = Yojson.Safe.t

  let to_string json = Yojson.Safe.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
      |> Util.My_list.filter_map (fun (k, v) ->
             match k with `String k -> Some (k, v) | _ -> None ) )
end

module Encode = Encode.Make (Json_encodeable)
OCaml

Innovation. Community. Security.