使用 bs-json 解码根目录中带有动态键的对象
Using bs-json to Decode object with dynamic keys in root
我正在尝试将以下 JSON 对象解码为 Reason 对象。
{"AAPL":{"price":217.36}}
对象根中的键是动态的。
以下通用示例在密钥不在根目录中时有效。我将如何更改它以使其适用于根目录中的动态密钥?
module Decode = {
let obj = json =>
Json.Decode.{
static: json |> field("static",string),
dynamics: json |> field("dynamics", dict(int)),
};
};
如果您的数据如下所示:
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
我正在尝试将以下 JSON 对象解码为 Reason 对象。
{"AAPL":{"price":217.36}}
对象根中的键是动态的。
以下通用示例在密钥不在根目录中时有效。我将如何更改它以使其适用于根目录中的动态密钥?
module Decode = {
let obj = json =>
Json.Decode.{
static: json |> field("static",string),
dynamics: json |> field("dynamics", dict(int)),
};
};
如果您的数据如下所示:
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