Skip to content

Instantly share code, notes, and snippets.

@jszmajda
Last active September 9, 2017 00:33
Show Gist options
  • Save jszmajda/13097b1e5240e43df960090b22be6659 to your computer and use it in GitHub Desktop.
Save jszmajda/13097b1e5240e43df960090b22be6659 to your computer and use it in GitHub Desktop.
Elm JSON Decoding
-- So I'm decoding JSON with this pattern, but there has to be a better way
import Json.Decode as JD
type alias User =
{ id : Int
, email : String
, firstName : String
, lastName : String
}
-- specifically here: this map4 seems dumb. This function depends on the proper
-- ordering of the fields to match the record constructor above. There must be
-- a better way, right?
jsonDecoder : JD.Decoder User
jsonDecoder = JD.map4 User
(JD.field "id" int)
(JD.field "email" string)
(JD.field "firstName" string)
(JD.field "lastName", string)
@dvdsgl
Copy link

dvdsgl commented Sep 9, 2017

Hey! I built this tool to output Elm decoders for JSON: https://elm.quicktype.io/

Here's an order-independent decoder that it built given your User type:

otherUser : Jdec.Decoder OtherUser
user =
    Jpipe.decode User
        |> Jpipe.required "email" Jdec.string
        |> Jpipe.required "firstName" Jdec.string
        |> Jpipe.required "id" Jdec.int
        |> Jpipe.required "lastName" Jdec.string

It uses NoRedInk/elm-decode-pipeline.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment