How to read a YAML file from Haskell
While working on BrainCandy (My first Haskell web application), I needed a way to load in some database configuration. As I use YAML quite frequently in other languages such as Java, I thought it would be nice to use it through Haskell as well. After a bit of SO and Google I came across a few good examples that helped me get started. (See the references for more details.)
Given how easy it is to read YAML through Haskell, I thought I’d write a very short example to get people started.
The config.yml file:
username: "John Smith"
password: "Sm1thy@Jon0"
The Haskell code to read the config.yml file:
{-# LANGUAGE DeriveGeneric #-} -- (2)
import qualified Data.ByteString.Char8 as BS
import qualified Data.Yaml as Y
import GHC.Generics
import Data.Aeson
data Cred = Cred { username :: String, password :: String } deriving (Show, Generic) -- (1,2)
instance FromJSON Cred -- (3)
main :: IO ()
= do
main <- BS.readFile "config.yml" -- (4)
content let parsedContent = Y.decode content :: Maybe Cred -- (5)
case parsedContent of
Nothing -> error "Could not parse config file."
Just (Cred u p)) -> putStrLn ("username: " ++ u ++ ", password: " ++ p) (
Here are the basic steps:
- Create a datatype to match the YAML structure of your config file. Creds in this case.
- Make sure your datastructure derives Show and Generic. You need to use {-# LANGUAGE DeriveGeneric #-} to derive Generic instances.
- Create an Aeson.FromJSON instance of your datatype.
- Read the content of your config file as ByteString .
- Pass file contents to the Data.Yaml.decode function. The Data.YAML.decode function returns a Maybe Cred as it might not be able to parse the config file into the supplied data structure.
The cabal project for this example can be found on github.
Now go externalize those configurations!
References: