Search code examples
jsonocamlreasonbucklescript

How to encode a list of records to JSON in Reason?


Given a record type and a list of records:

type note = {
  text: string,
  id: string
};

let notes: list complete_note = [{text: "lol", id: "1"}, {text: "lol2", id: "2"}]

How do I encode this to JSON using bs-json module?

What I tried: I tried to manually create JSON string using string interpolation in bucklescript, but that's definitely not something I want to do :)

notes
|> Array.of_list
|> Array.map (
  fun x => {
    // What should I do?
  }
)
|> Json.Encode.stringArray
|> Js.Json.stringify;

Solution

  • Disclaimer, I'm not a Reason expert, so the code might be non-idiomatic. It may also have errors, as I don't have the BuckleScript installed, so I didn't test it.

    So, if you want to represent each note as a JSON object with text and id fields, then you can use the Js.Json.objectArray function to create a JSON document from an array of JS dictionaries. The easiest way to create a dictionary would be to use the Js.Dict.fromList function, that takes a list of pairs.

    notes
    |> Array.of_list
    |> Array.map (fun {id, text} => {
      Js.Dict.fromList [("text", Js.Json.string text), ("id", Js.Json.string id)]
    })
    |> Js.Json.objectArray
    |> Js.Json.stringify;