【问题标题】:How can I parse this JSON to a record type?如何将此 JSON 解析为记录类型?
【发布时间】:2018-06-04 16:24:41
【问题描述】:

我有一些数据将在运行时获取:

/* {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 多行。

【问题讨论】:

    标签: json reason bucklescript


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2022-08-10
      • 2020-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多