在Haskell中读取YAML对象列表

时间:2014-01-22 19:42:44

标签: parsing haskell yaml

假设这个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]。我怎么能这样做?

1 个答案:

答案 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