data User = User { city :: Text
                 , country :: Text
                 , phone :: Text
                 , email :: Text}

instance ToJSON User where
    toJSON (User a b c d)= object ["a" .= a
                                  ,"b" .= b
                                  ,"c" .= c
                                  ,"d" .= d]

test:: User -> IO Value
test u = do
    let j = toJSON u
    return j

我想要的是这样的文字
test::User -> IO Text
test u = do
    let j = pack ("{\"city\":\"test\",\"country\":\"test\",\"phone\":\"test\",\"email\":\"test\"}")
    return j

我不知道如何从值到文本

最佳答案

要做到这一点,要比通常(我认为)有用的功能要困难得多。 Data.Aeson.Encode.encode进行了大量工作,并将其一直转换为ByteString

encode开始并将Lazy.Text -> ByteString转换为Lazy.Text -> Strict.Text转换即可满足您的需求:

{-# LANGUAGE OverloadedStrings #-}

import Data.Aeson
import Data.Aeson.Encode (fromValue)
import Data.Text
import Data.Text.Lazy (toStrict)
import Data.Text.Lazy.Builder (toLazyText)

data User = User
  { city    :: Text
  , country :: Text
  , phone   :: Text
  , email   :: Text
  }

instance ToJSON User where
  toJSON (User a b c d) = object
    [ "city"    .= a
    , "country" .= b
    , "phone"   .= c
    , "email"   .= d
    ]

test :: User -> Text
test = toStrict . toLazyText . encodeToTextBuilder . toJSON

关于haskell Data.Aeson.Value转换为文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11988853/

10-12 00:34
查看更多