elm-community / json-extra

Convenience functions for working with Json.
http://package.elm-lang.org/packages/elm-community/json-extra/latest
MIT License
35 stars 16 forks source link

dict2 fails when trying to decode string keys #22

Open malaire opened 5 years ago

malaire commented 5 years ago

This example

import Json.Decode exposing (..)

 """ { "hello": "world", "foo": "bar" } """
    |> decodeString (dict2 string string)

gives following error:

Problem with the given value: "hello"
This is not valid JSON!
JSON.parse: unexpected character at line 1 column 1 of the JSON data <internals>
lydell commented 4 years ago

dict2 tries to parse the keys as JSON here for some reason:

https://github.com/elm-community/json-extra/blob/14b45543fb85531385eb9ac9adca2c054f73e624/src/Json/Decode/Extra.elm#L192

1 is valid JSON, hello is not.

Maybe the signature of dict2 should be changed to:

dict2 : (String -> Decoder comparable) -> Decoder v -> Decoder (Dict comparable v)

-- with this:
case decodeValue (keyDecoder strKey) (Json.Encode.string strKey) of

If so, the dict2 int string example would become dict2 (String.toInt >> fromMaybe) string, and your dict2 string string example would become dict2 succeed string.

If one wants the current behavior, that can be done with dict2 (always (doubleEncoded keyDecoder)) valueDecoder.