Data.Aeson
安装 aeson
$ cabal install aeson
Installed aeson-1.2.3.0
Prelude> :m +Data.Aeson
Prelude Data.Aeson>
Data.Aeson 是一个处理 JSON 数据的库。
处理 Person
{-# LANGUAGE DeriveGeneric, OverloadedStrings #-}
import GHC.Generics
import Data.Aeson
import Data.Text
data Person = Person {
name :: Text
, age :: Int
} deriving (Generic, Show)
instance ToJSON Person where
toEncoding = genericToEncoding defaultOptions
instance FromJSON Person
*Main> :set -XOverloadedStrings
*Main> encode (Person {name = "Joe", age = 12})
"{\"name\":\"Joe\",\"age\":12}"
*Main> decode "{\"name\":\"Joe\",\"age\":12}" :: Maybe Person
Just (Person {name = "Joe", age = 12})
处理 AST
Prelude Data.Aeson> decode "{\"foo\": 123}" :: Maybe Value
Just (Object (fromList [("foo",Number 123.0)]))
Prelude Data.Aeson> decode "{\"foo\": [\"abc\",\"def\"]}" :: Maybe Value
Just (Object (fromList [("foo",Array [String "abc",String "def"])]))
Prelude Data.Aeson> decode "[1,2,3]" :: Maybe [Int]
Just [1,2,3]
Prelude Data.Aeson> decode "{\"foo\":1,\"bar\":2}" :: Maybe (Data.Map.Map String Int)
Just (fromList [("bar",2),("foo",1)])