如何将此 JSON 解析为记录类型?
How can I parse this JSON to a record type?
我有一些数据将在运行时获取:
/* {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 行长。
使用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)
};
我有一些数据将在运行时获取:
/* {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 行长。
使用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)
};