如何编码为YAML?

时间:2014-02-07 11:31:55

标签: haskell yaml

我找到了如何从YAML解码的解决方案

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"

    go :: Bool -> String -> IO()
    go pl force = do
        ymlData <- (</> "sync.yml")
            <$> takeDirectory 
            <$> getExecutablePath >>= \yml -> 
                doesFileExist yml >>= \isCfgEx ->
                    if isCfgEx then BS.readFile yml
                               else ...

        let users = Data.Yaml.decode ymlData :: Maybe [MyUser]
        print $ fromJust users

但似乎我尝试解码的并不是我所期望的并且没有任何东西......我尝试了:

users:
  - test:
      id: 1
      name: 'zz'
      reputation: 5

我该怎么编码?

1 个答案:

答案 0 :(得分:1)

您的YAML文件没有用户列表。你想在yaml文件中使用这样的东西 -

-   id: 1
    name: 'xx'
    reputation: 5
-   id: 2
    name: 'zz'
    reputation: 5