How can I parse this JSON to a record type?
Asked Answered
Z

1

5

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.

Zoilazoilla answered 30/4, 2017 at 0:38 Comment(0)
M
10

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)
  };
Misspeak answered 30/4, 2017 at 12:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.