阅读Haskell中的YAML对象列表 [英] Reading YAML lists of objects in Haskell
问题描述
假设这个YAML(保存在一个名为 users.yml
的文件中):
- id:1
名称:未知用户
声望:0
- id:2
名称:Foo bar
声望:4
和这个Haskell data
类型:
data MyUser = MyUser {id :: Int,
name :: String,
reputation :: Int}
导出(显示)
我想使用 yaml 库将YAML读入 [MyUser]
。我该怎么做?
FromJSON
实例(请注意,这被称为 FromJSON
,因为 yaml 是从 Aeson 库),如 Data.Yaml
文档。 以前讨论过与Aeson类似的问题,此处,而讨论了Haskell YAML库的选择这里
这是一个最小的工作示例, YAML文件转换为 [MyUser]
:
{ - #LANGUAGE OverloadedStrings # - }
导入Data.Yaml
导入Control.Applicative - < $> ;, < * GT;
import Data.Maybe(fromJust)
将合格的Data.ByteString.Char8导入为BS
data MyUser = MyUser {id :: Int,
name :: String,
reputation :: Int}
derived(Show)
instance FromJSON MyUser where
parseJSON(Object v)= MyUser< $>
v。:id< *>
v。:name< *>
v。:信誉
- 非对象值的类型错误,因此失败。
parseJSON _ =错误无法从YAML / JSON解析MyUser
main = do
ymlData< - BS.readFileusers.yml
let users = Data.Yaml.decode ymlData :: Maybe [MyUser]
- 打印它,仅用于显示
打印$ fromJust用户
Assuming this YAML (saved in a file called users.yml
):
- id: 1
name: Unknown user
reputation: 0
- id: 2
name: Foo bar
reputation: 4
and this Haskell data
type:
data MyUser = MyUser {id :: Int,
name :: String,
reputation :: Int}
deriving (Show)
I want to use the yaml library to read the YAML into a [MyUser]
. How can I do that?
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
这篇关于阅读Haskell中的YAML对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!