You need to create a FromJSON
instance (note that this is called FromJSON
as yaml is derived from the Aeson library) as described in the Data.Yaml
documentation.
A similar issue with Aeson was previously discussed here whereas the choice of a Haskell YAML library was discussed here
Here's a minimal working example that converts the YAML file into a [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