haskell/aeson

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

Open

#463 aperta il 27 ago 2016

Vedi su GitHub
 (2 commenti) (3 reazioni) (0 assegnatari)Haskell (334 fork)batch import
help wantedissue: breaking change

Metriche repository

Star
 (1298 star)
Metriche merge PR
 (Merge medio 89g 5h) (9 PR mergiate in 30 g)

Descrizione

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"]]

Guida contributor