aeson
aeson copied to clipboard
Mismatch between derived To/FromJSONKey and To/FromJSON instances for "strings"
I think this was an oversight and we need generics for To/FromJSONKey to make those instances match To/FromJSON.
The reason this happens is that deriving ToJSON for some types such as "enumerables" produces a string, but the ToJSONKey instance's default is always to produce an Array of arrays instead of an object, even when the key serializes to a string.
#!/usr/bin/env stack
-- stack --resolver nightly-2016-08-27 --install-ghc runghc --package aeson-1.0.0.0 --package semigroups-0.18.2 --package unordered-containers --package hashable
{-# LANGUAGE DeriveGeneric #-}
import Data.Aeson
import Data.Hashable
import GHC.Generics
import qualified Data.ByteString.Lazy.Char8 as L
import qualified Data.HashMap.Strict as H
data T = A | B deriving (Eq, Generic)
instance Hashable T
instance ToJSON T
instance ToJSONKey T
main :: IO ()
main = do
L.putStrLn $ encode A -- => "A"
L.putStrLn $ encode (H.fromList [(A, 'a')]) -- => [["A","a"]]
We could add
gToTextJsonKey
and friends, so the change can be done in backwards compatible way, i.e. you'll write
instance Hashable T
instance ToJSON T
instance ToJSONKey T
toJSONKey = gToJsonKeyText
Also, my gut feeling it would be much simpler to do this way, than try to conditionally do either one encoding, based on types' shape. We could do the breaking change later?
That sounds like a good first step!