JSON Decoders - did you get all the fields?

I had a similar problem recently, so I decided to create a small package for the problem this weekend: eike/json-decode-complete. It allows you to write object decoders that fail if you don’t handle all fields:

import Json.Decode exposing (Decoder)
import DecodeComplete exposing (..)

type alias User =
    { name : String
    , age : Int
    }

userDecoder : Decoder User
userDecoder =
    object User
        |> required "name" Decode.string
        |> required "age" Decode.int
        |> discard "email"
        |> complete

This decoder will fail if the provided JSON has fields other than name, age and email.

Unfortunately, my approach requires first decoding into a Dict String Decode.Value and then decoding the elements which degrades the error messages because I have to re-throw them with fail. Maybe there is a better way to implement this?

1 Like