I wanted to show off a technique I’ve been experimenting with, mapping to/from JSON with custom-types.
I have a SPA application that uses automatic message-replay as part of the development-setup. This in turn requires me to maintain a
Json.Decode.Decoder Msg and
Msg -> Json.Encode.Value functions.
The “problem” for me is having to maintain a mapping from/to JSON for a custom-type. Encoding allows you to do nice exhaustive type-checking, but decoders do not. I would like to have a more maintainable approach to mapping between Elm/JSON values.
the JSON encode-function is mapping
customType -> Json.Encode.Value. Since this mapping has exhaustive pattern-matching, I could perhaps modify its definition to:
- Return both an encoding of the value, along with a decoder for it?
- using a loop-function, generate a list of all variants, map them to decoders, and join them with
I’ve tried to make an Ellie, but couldn’t save it, so here’s a gist of the idea. The code is brittle, but should illustrate my approach, and could perhaps be a starting-point for a nice API?
Let me know if you have suggestions for improvements, simplifications, or whatever you think!