Source

spotxtras / xjson.ml

Full commit
open Spotlib.Spot
open Meta_conv.Result.Open
open Tiny_json

let ocaml_of_t : Json.t Ocaml_conv.encoder = fun j -> Ocaml.String (Json.show j)
let t_of_ocaml : Json.t Ocaml_conv.decoder = fun ?(trace=[]) o ->
  try match o with
  | Ocaml.String s -> `Ok (Json.parse s)
  | _ -> failwith "Ocaml.String expected"
  with e -> `Error (Meta_conv.Error.Exception e, o, trace)

let parse s = try `Ok (Json.parse s) with e -> `Error (`Json_parse e)

module Error = struct
  open Format

  type t = [ `Json_parse of exn
           | `Json_conv of Json.t Meta_conv.Error.t
           | Xcurl.Error.t
           ]

  let wrap_json_conv (convf : 'a Json_conv.decoder) s = match convf s with
    | `Ok v -> `Ok v
    | `Error e -> `Error (`Json_conv e)

  let format ppf = function
    | `Json_parse exn -> fprintf ppf "Error at Json parse: %s@." (Printexc.to_string exn)
    | `Json_conv e -> Json_conv.format_full_error ppf e 
    | #Xcurl.Error.t as e -> Xcurl.Error.format ppf e

end

let curl_get_and_parse (convf : 'a Json_conv.decoder) curlf = 
  Xcurl.get_string curlf >>= parse >>= Error.wrap_json_conv convf