nvie/decoders

How to decode recursive data structures?

svdHero opened this issue · 4 comments

Hi there,

how would I decode recursive data structures, such as

type Folder = {
    name: string,
    subfolders: Folder[]
}

Elm has the lazy decoder for this:
https://package.elm-lang.org/packages/elm/json/latest/Json-Decode#lazy

How would I solve this using this decoders package?

nvie commented

Great point! This has been on my list to implement, but I seem to have forgotten about it. I've implemented it in #511 and am still running a few tests with it. I'll make a new release with this lazy decoder included as soon as I'm happy with the results.

nvie commented

With this new decoder, the following should be possible:

import { array, Decoder, guard, lazy, object, string } from "decoders";

type Folder = {
  name: string;
  subfolders: Folder[];
};

const folder: Decoder<Folder> = object({
  name: string,
  subfolders: array(lazy(() => folder)),
});
nvie commented

Now available in v1.21.0.

Awesome. Thanks a lot.