Skip to content

Instantly share code, notes, and snippets.

@ashishnegi
Last active September 4, 2016 16:55
Show Gist options
  • Save ashishnegi/a4ee5b22b4369b4d8f7cc0a0400aae75 to your computer and use it in GitHub Desktop.
Save ashishnegi/a4ee5b22b4369b4d8f7cc0a0400aae75 to your computer and use it in GitHub Desktop.
-- Sometimes we want to decode value of type a from a json list of a.. but each with some little differences..
-- Like server sends json: [{"name" : "a"},{"name" : "b"}]
-- and we have
type alias Player =
{ name : String
, color : Color
}
-- color is view specific and server is not sending it..
-- so we have a function :
decodePlayer : Color -> Decoder Player
decodePlayer color =
Decode.object (\name -> Player name color) ("name" : Decode.string)
-- so.. now we can decode above json array with decodeList
decodeList (List.map decodePlayer [Color.red, Color.blue, Color.green])`
-- where decodeList is below..
decodeList : List (Decoder a) -> Decoder (List a)
decodeList decoders =
Decode.customDecoder
(Decode.list Decode.value)
(\jsonList ->
List.foldr (Result.map2 (::)) (Ok [])
(List.map2 (\decoder json -> Decode.decodeValue decoder json)
decoders jsonList))
-- see documentation of Decode.customDecoder / Decode.value for more details.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment