Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

haskell Data.Aeson.Value to Text

Tags:

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

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

like image 251
Gert Cuykens Avatar asked Aug 16 '12 14:08

Gert Cuykens


1 Answers

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
like image 59
Nathan Howell Avatar answered Sep 20 '22 19:09

Nathan Howell