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
What I want is Text like so
test::User -> IO Text
test u = do
let j = pack ("{\"city\":\"test\",\"country\":\"test\",\"phone\":\"test\",\"email\":\"test\"}")
return j
I can't figure it out how to go from Value to Text
It is more difficult to do this than it should be for what (I think) is a generally useful function. Data.Aeson.Encode.encode
does too much work and converts it all the way to a ByteString
.
Starting with encode
and switching the Lazy.Text -> ByteString
to Lazy.Text -> Strict.Text
conversion does what you want:
{-# 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With