Search code examples
reasonbucklescriptbs-json

Using bs-json to Decode object with dynamic keys in root


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)),
    };
};

Solution

  • 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