36
0%
Apache-2.0
unpublishedneglectedJSON combinator library for BuckleScript/Reason

JsonCodec

JSON combinator library for BuckleScript/Reason

Using the magic of pickler combinators, this library allows you to parse and serialize JSON structures in a declarative way, free of boilerplate.

Here's a little example:

  • RE
  • ML
let json = {js|
{
    "name": "Great Pyramid of Giza",
    "lat": 29.979175,
    "lon": 31.134358,
    "height": 146.5
}
|js};

/* Define a codec for the above object type */
let codec =
  JsonCodec.(
    object4(
      field("name", string),
      field("lat", number),
      field("lon", number),
      field("height", number),
    )
  );

/* Decoding */
switch (JsonCodec.decodeJson(codec, json)) {
| Belt.Result.Ok((name, lat, lon, height)) =>
  Printf.printf("name='%s' location=%f,%f height=%f\n", name, lat, lon, height)
| Belt.Result.Error(error) => Printf.printf("Decoding error: %s", error)
};

/* Encoding */
let encoded =
  JsonCodec.encodeJson(codec, ("Machu Picchu", -13.163333, -72.545556, 2430.0));

Printf.printf("JSON: %s\n", encoded);
let json =
  {js|
{
    "name": "Great Pyramid of Giza",
    "lat": 29.979175,
    "lon": 31.134358,
    "height": 146.5
}
|js}
let codec =
  let open JsonCodec in
    object4 (field "name" string) (field "lat" number) (field "lon" number)
      (field "height" number)
let _ =
  match JsonCodec.decodeJson codec json with
  | ((Belt.Result.Ok ((name,lat,lon,height)))[@explicit_arity ]) ->
      Printf.printf "name='%s' location=%f,%f height=%f\n" name lat lon
        height
  | ((Belt.Result.Error (error))[@explicit_arity ]) ->
      Printf.printf "Decoding error: %s" error
let encoded =
  JsonCodec.encodeJson codec
    ("Machu Picchu", (-13.163333), (-72.545556), 2430.0)
let _ = Printf.printf "JSON: %s\n" encoded

© 2017-2018 State Machine Systems Ltd. Apache Licence, Version 2.0