How can I parse this JSON into a record type?

I have some data that I will retrieve at runtime:

/* {id: 1, name: 'brad', age: 27, address: { city: 'city1', state: 'state1' } } */
let data = "{\"id\":1,\"name\":\"brad\",\"age\":27,\"address\":{\"city\":\"city1\",\"state\":\"state1\"}}";

Using ReasonML and BuckleScript, how can I get this data in the form:

type address = {
  city: string,
  state: string
};

type person = {
  id: int,
  name: string,
  age: option int,
  address: option address
};

The solution I came up with is 100 lines of long string.

+4
source share
1 answer

Using bs-json (this is a very big job):

let parseAddress json =>
  Json.Decode.{
    city: json |> field "city" string,
    state: json |> field "state" string
  };

let parsePerson json =>
  Json.Decode.{
    id: json |> field "id" int,
    name: json |> field "name" string,
    age: json |> optional (field "age" int),
    address: json |> optional (field "address" parseAddress)
  };
+3
source

Source: https://habr.com/ru/post/1676008/


All Articles