Haskell语言学习笔记(66)Aeson

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)

data Persons = Persons {
      persons :: [Person]
    } deriving (Generic, Show)

instance ToJSON Persons where
    toEncoding = genericToEncoding defaultOptions

instance FromJSON Persons

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})
*Main> encode (Persons {persons = [Person {name = "Joe", age = 12}]})
"{\"persons\":[{\"name\":\"Joe\",\"age\":12}]}"
*Main> decode "{\"persons\":[{\"name\":\"Joe\",\"age\":12}]}" :: Maybe Persons
Just (Persons {persons = [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)])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值