Source

spotxtras / xjson.ml

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

(* CR jfuruse: can be shared with other json apps *)
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)

(* CR jfuruse: can be shared with other json apps *)
module Error = struct
  open Format

  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
    | `Http (n, _err) -> fprintf ppf "HTTP Error %d@." n
    | `Json_parse exn -> fprintf ppf "Error at Json parse: %s@." (Printexc.to_string exn)
    | `Other exn      -> fprintf ppf "Error: %s@." (Printexc.to_string exn)
    | `Json_conv e -> Json_conv.format_full_error Format.stderr e 

  let from_Ok = function
    | `Ok v -> v
    | `Error e -> failwith (Format.sprintf "%a" format e)
end

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