Advertisement
Guest User

Untitled

a guest
Nov 8th, 2018
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 0.83 KB | None | 0 0
  1. open Belt;
  2.  
  3. [@bs.deriving abstract]
  4. type fullName = {
  5.   first: string,
  6.   last: string,
  7. };
  8.  
  9. [@bs.deriving abstract]
  10. type person = {
  11.   name: fullName,
  12.   age: int,
  13. };
  14.  
  15. let person1 = person(~name=fullName(~first="Ricky", ~last="Zhang"), ~age=10);
  16.  
  17. /* encode person1, then decode it */
  18. let json = person1->Js.Json.stringifyAny->Option.getExn->Js.Json.parseExn;
  19.  
  20. let name =
  21.   json
  22.   ->Js.Json.decodeObject
  23.   ->(Option.flatMap(p => Js.Dict.get(p, "name")))
  24.   ->(Option.flatMap(json => Js.Json.decodeObject(json)))
  25.   ->Option.getExn;
  26.  
  27. let firstName =
  28.   Js.Dict.get(name, "first")
  29.   ->(Option.flatMap(json => Js.Json.decodeString(json)))
  30.   ->Option.getExn;
  31.  
  32. let lastName =
  33.   Js.Dict.get(name, "last")
  34.   ->(Option.flatMap(json => Js.Json.decodeString(json)))
  35.   ->Option.getExn;
  36.  
  37. Js.log({j|Hello, $firstName $lastName|j});
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement