4

我正在尝试将以下 JSON 对象解码为 Reason 对象。

{"AAPL":{"price":217.36}}

对象根中的键是动态的。

以下一般示例在密钥不在根目录中时有效。我将如何更改它以使其适用于根目录中的动态键?

module Decode = {
    let obj = json =>
    Json.Decode.{
      static: json |> field("static",string),
      dynamics: json |> field("dynamics", dict(int)),
    };
};
4

1 回答 1

4

如果您的数据如下所示:

let data = {| {
  "AAPL": { "price": 217.36 },
  "ABCD": { "price": 240.5 }
} |};

您可以获得Js.Dict以下内容:

module Decode = {
  open Json.Decode;
  let price = field("price", float);
  let obj = dict(price);
};

let decodedData = data |> Json.parseOrRaise |> Decode.obj;

let _ = decodedData->(Js.Dict.unsafeGet("AAPL")) |> Js.log;

它应该打印217.36

于 2018-10-16T09:19:14.153 回答