Haskell aeson package basic usage

228 views Asked by At

Working my way through Haskell and I'm trying to learn how to serialized to/from JSON.

I'm using aeson-0.8.0.2 & I'm stuck at basic decoding. Here's what I have:

file playground/aeson.hs:

{-# LANGUAGE OverloadedStrings #-}

import Data.Text
import Data.Aeson

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


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

    parseJSON _          = mzero


main = do
    let a = decode "{\"name\":\"Joe\",\"age\":12}" :: Maybe Person
    print "aa"

ghc --make playground/aeson.hs yields:

[1 of 1] Compiling Main ( playground/aeson.hs, playground/aeson.o )

playground/aeson.hs:13:35: Not in scope: `'

playground/aeson.hs:14:40: Not in scope: `<*>'

playground/aeson.hs:17:28: Not in scope: `mzero'

  1. Any idea what I'm doing wrong?
  2. Why is OverloadedString needed here?
  3. Also, I have no idea what <$>, <*>, or mzero are supposed to mean; I'd appreciate tips on where I can read about any of these.
2

There are 2 answers

0
bheklilr On BEST ANSWER

You need to import Control.Applicative and Control.Monad to get <$>, <*> and mzero. <$> just an infix operator for fmap, and <*> is the Applicative operator, you can think of it as a more generalized form of fmap for now. mzero is defined for the MonadPlus class, which is a class representing that a Monad has the operation

mplus :: m a -> m a -> m a

And a "monadic zero" element called mzero. The simplest example is for lists:

> mzero :: [Int]
[]
> [1, 2, 3] `mplus` [4, 5, 6]
[1, 2, 3, 4, 5, 6]

Here mzero is being used to represent a failure to parse. For looking up symbols in the future, I recommend using hoogle or FP Complete's version. Once you find the symbol, read the documentation, the source, and look around for examples of its use on the internet. You'll learn a lot by looking for it yourself, although it'll take you a little while to get used to this kind of research.

The OverloadedStrings extension is needed here because the Aeson library works with the Text type from Data.Text instead of the built-in String type. This extension lets you use string literals as Text instead of String, just as the numeric literal 0 can be an Int, Integer, Float, Double, Complex and other types. OverloadedStrings makes string literals have type Text.String.IsString s => s instead of just String, so it makes it easy to use alternate string-y types.

0
ErikR On

For <$> you need to import Control.Applicative and for mzero you need to import Control.Monad.

You can determine this by using the web-based version of hoogle (http://www.haskell.org/hoogle) or the command line version:

$ hoogle '<$>'
$ hoogle mzero