【问题标题】:Decoding a JSON array of objects解码 JSON 对象数组
【发布时间】:2018-04-19 21:06:37
【问题描述】:

假设我有这个 JSON 对象数组:

[
  {"name": "foo", "tags": ["bird", "animal"], "age": 10},
  {"name": "bar", "tags": ["dog", "animal"], "age": 5},
  {"name": "baz", "tags": ["cat", "animal"], "age": 3}
]

如何在 ReasonML 中解码?

【问题讨论】:

    标签: json reason bucklescript


    【解决方案1】:

    使用bs-json将其解码为记录数组:

    let data = {|[
      {"name": "foo", "tags": ["bird", "animal"], "age": 10},
      {"name": "bar", "tags": ["dog", "animal"], "age": 5},
      {"name": "baz", "tags": ["cat", "animal"], "age": 3}
    ]|};
    
    type t = {
      name: string,
      tags: array(string),
      age: int
    };
    
    module Decode = {
      let item = json =>
        Json.Decode.{
          name: json |> field("name", string),
          tags: json |> field("tags", array(string)),
          age:  json |> field("age", int)
        };
    
      let all =
        Json.Decode.array(item)
    };
    
    let result: array(t) =
      data |> Json.parseOrRaise
           |> Decode.all;
    

    【讨论】:

      猜你喜欢
      • 2011-02-05
      • 1970-01-01
      • 2017-01-12
      • 1970-01-01
      • 2020-07-01
      • 2018-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多