Ocaml - Json Encoding and Decoding

Posted on November 26, 2018

I usually have trouble serializing/deserializing json when I first learn a staticly typed language. I had the same experience with C# and in Haskell. Luckily, there’s a lot of resources and it’s easy to understand. This time I’m learning Ocaml/Bucklescript and I’m encoutering the same thing. Good thing bucklescript’s standard library provides Js.Json.

JSON Encoding

Creating a simple json object.

Creating json from a record. First, create the record type.

Then create a record value.

Now, a function that will serialize the record.

To see the output in the console.

JSON Decoding

I’m gonna do the other way around in this next section. Deserializing json! When I get a json object I will transform it into personRec record.

Let’s say this is the json object I get.

First, I need to define a record since there’s no such thing as anonymous records in Ocaml.

I’ll use [@@bs.deriving abstract] decoractor for maninpulating json since Ocaml’s data representation is not really the same with javascript, and also it will give me convenience functions to access the fields.

I’ll create a utility function to help me extract json.

This will be my main decoding function

To simulate a json object I’ll make jsonPerosn.

To view the output

Using bs-json

JSON Encoding

I’ll encode a record using bs-json to turn it into a json object. First, I’ll create the record type.

Then, the record itself.

Next, will be the function to create the json object from the record

To view the output in the console.

JSON Decoding

I’m expecting the same json from above.

Define the person record.

Then, the function to transform the record to a json object.

To see the output in the console