4

I am trying to decode the following JSON object into a Reason object.

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

The key in the root of the object is dynamic.

The following general example works when the key is not in the root. How would I change it so it works for a dynamic key in the root?

module Decode = {
    let obj = json =>
    Json.Decode.{
      static: json |> field("static",string),
      dynamics: json |> field("dynamics", dict(int)),
    };
};
glennsl
  • 28,186
  • 12
  • 57
  • 75
Sepehr Sobhani
  • 862
  • 3
  • 12
  • 29

1 Answers1

4

If your data looks like:

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

You can get a Js.Dict with the following:

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;

It should print 217.36

csb
  • 674
  • 5
  • 13