2

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;
glennsl
  • 28,186
  • 12
  • 57
  • 75
Michał Miszczyszyn
  • 11,835
  • 2
  • 35
  • 53
  • I don't see how definining another type for `line` and `point` relates to my problem. I don't want to use yojson, which is a JSON engine written in Ocaml, I want to use bs-json to utilise native JSON handling in the browsers. – Michał Miszczyszyn Jul 12 '17 at 10:27
  • That doesn't answer any of my questions. I said I'm using `bs-json` but there's no example of encoding records. – Michał Miszczyszyn Jul 12 '17 at 10:32
  • Thank you, but there are no examples for encoding records. – Michał Miszczyszyn Jul 12 '17 at 10:37
  • 1
    You'll have to translate that record to a `Js.Dict` and then encode using `object_`: https://github.com/BuckleTypes/bs-json/blob/46f588df94c25da7d38aaf1092472f2d40babed9/__tests__/json_encode_test.ml#L25-L28 – Ionuț G. Stan Jul 12 '17 at 13:44

1 Answers1

3

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;
glennsl
  • 28,186
  • 12
  • 57
  • 75
ivg
  • 34,431
  • 2
  • 35
  • 63