Last active
September 4, 2016 16:55
-
-
Save ashishnegi/a4ee5b22b4369b4d8f7cc0a0400aae75 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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