Skip to content

HOWTO decode into records? #20

@justgage

Description

@justgage

Just some nice examples in the README.md would go a long way.

Love the idea of this library by the way ❤️.

One thing I was hoping to find: How do you convert a some JSON into a record? In Elm you would use something like: http://package.elm-lang.org/packages/elm-lang/core/5.1.1/Json-Decode#map or perhaps http://package.elm-lang.org/packages/NoRedInk/elm-decode-pipeline/latest

Example in Elm using elm-decode-pipeline

import Json.Decode exposing (int, string, float, Decoder)
import Json.Decode.Pipeline exposing (decode, required, optional, hardcoded)

-- basically a record in Elm
type alias User =
  { id : Int
  , email : Maybe String
  , name : String
  , percentExcited : Float
  }


userDecoder : Decoder User
userDecoder =
  decode User
    |> required "id" int
    |> required "email" (nullable string) -- `null` decodes to `Nothing`
    |> optional "name" string "(fallback if name is `null` or not present)"
    |> hardcoded 1.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions