Search code examples
jsonreasonbucklescript

How can I parse this JSON to a record type?


I have some data I'll be fetching 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 can 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've come up with are 100s of lines long.


Solution

  • Using bs-json:

    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)
      };