Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support decoding and encoding Dicts #14

Open
polux opened this issue Apr 15, 2016 · 2 comments
Open

Support decoding and encoding Dicts #14

polux opened this issue Apr 15, 2016 · 2 comments

Comments

@polux
Copy link

polux commented Apr 15, 2016

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
Copy link
Owner

eeue56 commented Apr 17, 2016

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
Copy link

Simply use the one in Json.Encode. Extra!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants