Support decoding and encoding Dicts
Opened this issue · 2 comments
polux commented
It would be great if, when fed with a type alias aliasing to a Dict
, the tool would produce decoders and encoders that make use of Json.Decode.dict
and Json.Encode.object
.
eeue56 commented
Work involved here:
Dict a b
should translate to
convertToTypedDict : Decoder a -> Dict String b -> Dict a b
convertToTypedDict decoder dict =
Dict.toList dict
|> List.filterMap (\(x, y) -> (Json.Decode.decodeString decoder x |> Result.toMaybe, y))
|> Dict.fromList
decodeDict : Decoder (Dict a b)
decodeDict =
Json.Decode.dict b
|> (flip Json.Decode.andThen) (convertToTypedDict)
encodeDict = (b -> Json.Encode.value) -> Dict a b -> Json.Encode.value
encodeDict encoder dict =
Dict.toList dict
|> List.map (\(x, y) -> (toString x, encoder y))
|> Json.Enocde.object
Might be a bit much since technically in JSON you're only allow strings as names.
Erudition commented
Simply use the one in Json.Encode. Extra!