haskell Data.Aeson.Value to Text

时间:2012-08-16 14:00:51

标签: haskell

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

我无法弄清楚如何从价值转向文本

2 个答案:

答案 0 :(得分:12)

这样做比应该更加困难(我认为)是一个通常有用的功能。 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

答案 1 :(得分:1)

Per Thomas的评论:您不是从Value转到Text,而是从Value转到ByteStringsendTextData函数的多态性足以接受ByteString s。