我有一些我将在运行时获取的数据:
/* {id: 1, name: 'brad', age: 27, address: { city: 'city1', state: 'state1' } } */
let data = "{\"id\":1,\"name\":\"brad\",\"age\":27,\"address\":{\"city\":\"city1\",\"state\":\"state1\"}}";
使用ReasonML和BuckleScript,我如何才能以下列形式获取此数据:
type address = {
city: string,
state: string
};
type person = {
id: int,
name: string,
age: option int,
address: option address
};
我提出的解决方案是100多行。
答案 0 :(得分:9)
使用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)
};