我正在尝试将下面的JSON对象解码为一个原因对象。
{"AAPL":{"price":217.36}}
对象根中的键是动态的。
下面的一般示例在键不在根时工作。我将如何更改它,使其工作在根中的动态键?
module Decode = {
let obj = json =>
Json.Decode.{
static: json |> field("static",string),
dynamics: json |> field("dynamics", dict(int)),
};
};发布于 2018-10-16 09:19:14
如果您的数据如下所示:
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
https://stackoverflow.com/questions/52828145
复制相似问题