Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Aeson JSON Library ByteString Issue

Tags:

haskell

aeson

I'm having trouble finding a function or workaround to convert a String to Data.ByteString.Lazy.Internal.ByteString

One of the functions in the Aeson Json library is decode and has the following description:

decode :: FromJSON a => bytestring-0.10.0.2:Data.ByteString.Lazy.Internal.ByteString -> Maybe a

I've tried using the pack function in Data.ByteString.Lazy.Char8 but that returns a different ByteString. Any one know how this can be fixed?

The following is the example I'm working on:

import Data.Aeson
import Data.Text
import Control.Applicative
import Control.Monad (mzero)
import qualified Data.ByteString.Lazy.Internal as BLI
import qualified Data.ByteString.Lazy.Char8 as BSL

data Person = Person 
    { name :: Text
    , age :: Int 
    } deriving Show

instance FromJSON Person where 
    parseJSON (Object v) = Person <$>
                   v .: (pack "name") <*>
                   v .: (pack "age")
    parseJSON _          = mzero

I tried using decode (BSL.pack "{\"name\":\"Joe\",\"age\":12}") :: Maybe Person and got the following error message:

Couldn't match expected type `bytestring-0.10.0.2:Data.ByteString.Lazy.Internal.ByteString'
                with actual type `BSL.ByteString'
    In the return type of a call of `BSL.pack'
    In the first argument of `decode', namely
      `(BSL.pack "{\"name\":\"Joe\",\"age\":12}")'
    In the expression:
        decode (BSL.pack "{\"name\":\"Joe\",\"age\":12}") :: Maybe Person

Help!

like image 948
MathanMV Avatar asked Aug 12 '26 04:08

MathanMV


1 Answers

You need to convert Char to Word8 using c2w (in Data.ByteString.Internal)

Data.ByteString.Lazy.pack $ map c2w "abcd"

I wrote out the fully qualified name for pack also to guarantee using the correct one, but you can clean this up in the imports section. When I run

> :t Data.ByteString.Lazy.pack $ map c2w "abcd"

I get ":: Data.ByteString.Lazy.Internal.ByteString"

Remember that Data.ByteString.Lazy represents strings of number values (you can't even run its pack on strings, you need to supply an array of numbers "pack [1, 2, 3, 4]"), so you might actually want to use the char equivalent Data.ByteString.Lazy.Char8.

like image 200
jamshidh Avatar answered Aug 15 '26 04:08

jamshidh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!