I’ve been playing with yojson
and notice it relies pretty heavily on exceptions, which I would like to avoid.
I was under the impression that it’s pretty much the go-to solution for JSON parsing in OCaml. Is that correct?
Is there a good alternative you’ve had a good experience with?
As a reference point, I’ve played with parsing with Angstrom too, and that’s pretty much the dev experience I want: make the non error state flow through the types as much as possible.
Here’s a little (messy and not quite correct) snippet of what I’m trying to achieve:
module U = Yojson.Safe.Util
let member str json =
try
let x = U.member str json in
Ok x
with
| _ -> Error "Oops"
;;
let conv s : (payload, string) result =
let ( let* ) = Result.bind in
let ( >>= ) = Result.bind in
let ( >|= ) = Result.map |> Fun.flip in
let root = Yojson.Safe.from_string s in
let* shipment_node = member "shipment" root in
let* tracking = shipment_node |> member "idShip" >|= U.to_string in
let* event_node = shipment_node |> member "event" >>= fun x -> Ok (U.to_list x) in
let* items = event_node |> to_items |> Option.to_result ~none:"No events!" in
let delivered =
List.fold_left
(fun acc x ->
if x.code = delivered_code then
Some { on = x.date; label = x.label }
else
acc)
None items
in
Ok { tracking; delivered; src = items }
Wrapping the raising functions as I did here with member
does not feel very practical, so I think I should probably switch library.