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

Mismatch between derived To/FromJSONKey and To/FromJSON instances for "strings" #463

Open
bergmark opened this issue Aug 27, 2016 · 2 comments

Comments

@bergmark
Copy link
Collaborator

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"]]
@phadej
Copy link
Collaborator

phadej commented Sep 12, 2016

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?

@bergmark
Copy link
Collaborator Author

That sounds like a good first step!

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

No branches or pull requests

2 participants