Decode json object with warning for unhandled keys

This is my attempt to decode keys but get warning when some key is not handled. Full example https://ellie-app.com/mxkGY5DVFa1/0.

Running this code will give this in browser console: [Warning]: I ran into afaildecoder: Unhandled field somefield: { url = "", amount = 0 }

Thanks @jessta for pointing to keyValuePairs. The code is base on this http://folkertdev.nl/blog/elm-messy-json-value/.

How can I make this more generic (less MyRecord) so I can reuse more code?
What can be improved, done differently?

module Main exposing (main)

import Html exposing (Html, text)
import Json.Decode exposing (..)


(|:) : Decoder (a -> b) -> Decoder a -> Decoder b
(|:) =
    map2 (<|)


serverResponseMy : String
serverResponseMy =
    """
    {
        "url": "https://elm-lang.org",
        "amount": 1.2,
        "somefield": 1
    }
"""


partialDecodeField : Decoder (List ( String, Value ))
partialDecodeField =
    keyValuePairs value


fromResultWithWarning : (String -> b -> Decoder b) -> ( String, Value ) -> b -> b
fromResultWithWarning decoder ( name, value ) record =
    case decodeValue (decoder name record) value of
        Ok newRecord ->
            newRecord

        Err error ->
            Debug.log ("[Warning]: " ++ error) record


feedNameL : (String -> MyRecord -> Decoder MyRecord) -> List ( String, Value ) -> MyRecord
feedNameL decoder elements =
    List.foldl (fromResultWithWarning decoder) defaultMyRecord elements


decodeList : Decoder MyRecord
decodeList =
    map (feedNameL decodeField) partialDecodeField


decodeField : String -> MyRecord -> Decoder MyRecord
decodeField name record =
    case name of
        "url" ->
            succeed (\url -> { record | url = url }) |: string

        "amount" ->
            succeed (\amount -> { record | amount = amount }) |: float

        _ ->
            fail <| "Unhandled field " ++ name


type alias MyRecord =
    { url : String
    , amount : Float
    }


defaultMyRecord : MyRecord
defaultMyRecord =
    MyRecord "" 0

main : Html msg
main =
    text <| toString <| decodeString decodeList serverResponseMy

I have a feeling there is a library package for this already, as I remember asking about it before. I’ll see if I can dig back on the old elm-discuss list and find it.

This one, I think:

http://package.elm-lang.org/packages/zwilias/json-decode-exploration/latest

https://groups.google.com/forum/#!searchin/elm-discuss/json$20missing$20fields|sort:date/elm-discuss/-WJRY3r8TDs/R57qsuKCAwAJ

Thanks, though I know about this library and strict mode. I wanted to do this with standard library as this is what you have to deal with in examples, libraries etc.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.