如何为类似的多态类型手动编写aeson ToJSON实例:
data Show a => Translatable a = Translatable (Map.Map String a)
deriving (Show, Eq, Typeable)
我想编码一个
Translatable $ Map.fromList [("key", "value"), ("key2", "value2")]
到一个像{ "key", "value", "key2", "value2" }
到目前为止,我尝试过的是:
import qualified Data.Aeson as A
import Data.Data (Typeable)
import qualified Data.Map as Map
data Show a => Translatable a = Translatable (Map.Map String a)
deriving (Show, Eq, Typeable)
instance Show a => A.ToJSON (Translatable a) where
toEncoding xs = A.object $ map (.=) (Map.toList xs)
错误
Couldn't match type ‘A.Value’
with ‘Data.Aeson.Encoding.Internal.Encoding' A.Value’
Expected type: A.Encoding
Actual type: A.Value
aeson文档显示:type Encoding = Encoding' Value
但是A.Encoding'不在范围之内
Not in scope: data constructor ‘A.Encoding'’
我在做什么错?
我将可翻译的类型更改为类型
type Translatable a = Map.Map String a
现在,它无需将Translatable作为实例添加到ToJSON即可工作>>
但是最初的问题仍然是问题。
如何为多态类型手动编写aeson ToJSON实例,例如:data Show a =>可翻译a =可翻译(Map.Map字符串a)派生(Show,Eq,Typeable)我想编码...] >
您正在混合toJSON
和toEncoding
功能。只需实现您的toJSON
实例的ToJSON
函数。我输入的Data.Aeson
不合格,以减少与操作员的争斗。
import Data.Aeson
import qualified Data.Text as T
--- etc.
instance Show a => ToJSON (Translatable a) where
toJSON (Translatable myMap) = toJSON
[ object [ T.pack key .= show val ] | (key, val) <- Map.toList myMap ]