You can try different decoders or provide a default value by using
Json.Decode.oneOf.
<http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Decode#oneOf>
Say that sometimes the "ingredients" field is missing or invalid, in which
case you want to return an empty list:
beerDecoder =
map4 Beer
(field "title" string)
(field "beer_type" string)
(field "description" string)
(oneOf [ field "ingredients" (list string), succeed [] ])
Or maybe sometimes it yields a string and sometimes a list:
field "ingredients" (oneOf [ list string, map (\x -> [x]) string) ])
Or maybe sometimes the whole data is garbage:
actualBeerDecoder =
oneOf [ beerDecoder, succeed (Beer "foo" "bar" "qux" [ "baz" ]) ]
In this case though you should use Decode.maybe and return a "List (Maybe
Beer)", and filter all the "Nothing" values like Joey said. Do not return
empty strings or empty records, that's what Maybe is for.
A more complex example from an API I'm using:
imageList : Decoder (List Url)
imageList =
oneOf
[ map (\x -> [x]) <| at [ "meta_single_page", "original_image_url" ]
string
, field "meta_pages" <| list <| at [ "image_urls", "original" ] string
]
Sometimes it yields just one image in the "meta_single_page" field,
sometimes a list of images in the "meta_pages" field.
To avoid having to deal with that later, I try the decoder for the single
image (and putting the result in a list, because I'm returning a list), and
if it fails I fall back to the decoder for the list of images.
--
You received this message because you are subscribed to the Google Groups "Elm
Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.