假设这个YAML(保存在名为users.yml
的文件中):
- id: 1
name: Unknown user
reputation: 0
- id: 2
name: Foo bar
reputation: 4
和这个Haskell data
类型:
data MyUser = MyUser {id :: Int,
name :: String,
reputation :: Int}
deriving (Show)
我想使用yaml库将YAML读入[MyUser]
。我怎么能这样做?
答案 0 :(得分:11)
您需要创建一个FromJSON
实例(请注意,这称为FromJSON
,因为 yaml 是从Aeson库派生的),如{ {3}}
先前已经讨论了与Aeson类似的问题Data.Yaml
documentation,而讨论了Haskell YAML库的选择here
这是一个将YAML文件转换为[MyUser]
:
{-# LANGUAGE OverloadedStrings #-}
import Data.Yaml
import Control.Applicative -- <$>, <*>
import Data.Maybe (fromJust)
import qualified Data.ByteString.Char8 as BS
data MyUser = MyUser {id :: Int,
name :: String,
reputation :: Int}
deriving (Show)
instance FromJSON MyUser where
parseJSON (Object v) = MyUser <$>
v .: "id" <*>
v .: "name" <*>
v .: "reputation"
-- A non-Object value is of the wrong type, so fail.
parseJSON _ = error "Can't parse MyUser from YAML/JSON"
main = do
ymlData <- BS.readFile "users.yml"
let users = Data.Yaml.decode ymlData :: Maybe [MyUser]
-- Print it, just for show
print $ fromJust users