Skip to content

Instantly share code, notes, and snippets.

@alicebob
Last active January 2, 2018 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alicebob/84083c48310cdb984fbe493d50aac905 to your computer and use it in GitHub Desktop.
Save alicebob/84083c48310cdb984fbe493d50aac905 to your computer and use it in GitHub Desktop.
elm decoder error
import Html exposing (..)
import Json.Decode exposing (Decoder, list, string)
import Json.Decode
type Elem
= Para (List Elem)
| Chunk String
elemListDecoder : Decoder (List Elem)
elemListDecoder =
Json.Decode.list elemDecoder
elemDecoder : Decoder Elem
elemDecoder =
Json.Decode.oneOf [ elemDecoderChunk, elemDecoderType ]
elemDecoderChunk : Decoder Elem
elemDecoderChunk =
Json.Decode.map Chunk string
elemDecoderType : Decoder Elem
elemDecoderType =
Json.Decode.field "type" string
|> Json.Decode.andThen elemDecoderTypeHelp
elemDecoderTypeHelp : String -> Decoder Elem
elemDecoderTypeHelp t =
case t of
"p" ->
-- meta: using elemDecoder directly doesn't work somehow
Json.Decode.map Para (Json.Decode.field "content" (Json.Decode.list elemDecoder))
-- Json.Decode.map Para (Json.Decode.field "content" (Json.Decode.list (Json.Decode.oneOf [ elemDecoderChunk, elemDecoderType])))
_ -> Json.Decode.fail <| "Can't do a " ++ t ++ " elem"
--- skeleton from here on
main =
Html.beginnerProgram { model = model, view = view, update = update }
model : Model
model =
let js = "[\"foo\", {\"type\": \"p\", \"content\": []}]"
in
case Json.Decode.decodeString elemListDecoder js of
Ok d -> { doc = d }
Err err -> Debug.crash err
-- MODEL
type alias Model = { doc : List Elem }
-- UPDATE
type Msg = Reset
update : Msg -> Model -> Model
update msg model =
case msg of
Reset -> model
-- VIEW
view : Model -> Html Msg
view model =
Html.text "all fine"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment