Question

I'm following the Aeson library documentation but their example doesn't seem to work for me:

Code:

 {-# LANGUAGE OverloadedStrings #-}

import Data.Text
import Data.Aeson
import Control.Applicative ((<$>),(<*>))
import Control.Monad

instance FromJSON Person where
  parseJSON (Object v) = Person <$>
                         v .: "name" <*>
                         v .: "age"
  -- A non-Object value is of the wrong type, so fail.
  parseJSON _          = mzero

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

Error report:

ghci> decode "{\"name\":\"Joe\",\"age\":12}" :: Maybe Person

Couldn't match expected type `Data.ByteString.Lazy.Internal.ByteString'
            with actual type `[Char]'
In the first argument of `decode', namely
  `"{\"name\":\"Joe\",\"age\":12}"'
In the expression:
    decode "{\"name\":\"Joe\",\"age\":12}" :: Maybe Person
In an equation for `a':
    a = decode "{\"name\":\"Joe\",\"age\":12}" :: Maybe Person

Am i doing something wrong here ?

Was it helpful?

Solution

The problem is that decode expects a ByteString and you are passing a String.

Try this in ghci:

:m +Data.ByteString.Lazy.Char8
decode $ pack "{\"name\":\"Joe\",\"age\":12}" :: Maybe Person

In real code you shouldn't use the Char8 module as it just truncates Chars to 8 bits without taking any account of encoding. Generally you should aim to start out with a ByteString, e.g. by reading it from disk using the functions in Data.ByteString.Lazy.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top