json-extra icon indicating copy to clipboard operation
json-extra copied to clipboard

dict2 fails when trying to decode string keys

Open malaire opened this issue 7 years ago • 1 comments

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>

malaire avatar Nov 30 '18 09:11 malaire

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.

lydell avatar Oct 20 '19 19:10 lydell