Reading lists of YAML objects in Haskell

Assuming this YAML (stored in a file with a name users.yml):

- id: 1
  name: Unknown user
  reputation: 0

- id: 2
  name: Foo bar
  reputation: 4

and this type of Haskell data:

data MyUser = MyUser {id :: Int,
                      name :: String,
                      reputation :: Int}
                      deriving (Show)

I want to use the yaml library to read YAML's [MyUser]. How can i do this?

+4
source share
1 answer

You need to create an instance FromJSON(note that this is called FromJSONsince yaml comes from the Aeson library), as described in the Data.Yamldocumentation .

Aeson , Haskell YAML

, 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
+11

All Articles