我如何操纵 Aeson 值?
How can I manipulate an Aeson value?
我正在尝试将一些具有标记元数据的博客文章解析为以分号分隔的字符串,例如:
#+title: Some Title
#+date: 2021-02-04
#+keywords: tag1; tag two; tag three
我有一个数据结构,我只需要让 Aeson 解析器按分号拆分。然而,事情似乎并没有这么简单:
data SrcMeta
= SrcMeta
{ title :: Text,
date :: Text,
tags :: [Text]
}
deriving (Show, Eq, Generic)
instance FromJSON SrcMeta where
parseJSON (Aeson.Object v) = do
title <- v Aeson..: "title"
date <- v Aeson..: "date"
tags <- T.splitOn ";" $ v Aeson..: "keywords"
return SrcMeta { title = title, date = date, tags = tags }
类型不匹配是T.splitOn
需要一个Text
,而.:
returns需要一个Parser
。我在想这个错误吗?将分号分隔的字符串解析为 [Text]
的最佳方法是什么?
您可以先检索 Text
然后拆分它,例如:
instance FromJSON SrcMeta where
parseJSON (Aeson.Object v) = do
title <- v Aeson..: "title"
date <- v Aeson..: "date"
<strong>tags <- v Aeson..: "keywords"</strong>
return SrcMeta { title = title, date = date, tags = <strong>T.splitOn ";" tags</strong> }
另一个选项是使用函子映射 (<$>) :: Functor f => (a -> b) -> f a -> f b
:
instance FromJSON SrcMeta where
parseJSON (Aeson.Object v) = do
title <- v Aeson..: "title"
date <- v Aeson..: "date"
tags <- <strong>T.splitOn ";" <$></strong> (v Aeson..: "keywords")
return SrcMeta { title = title, date = date, tags = tags }
我正在尝试将一些具有标记元数据的博客文章解析为以分号分隔的字符串,例如:
#+title: Some Title
#+date: 2021-02-04
#+keywords: tag1; tag two; tag three
我有一个数据结构,我只需要让 Aeson 解析器按分号拆分。然而,事情似乎并没有这么简单:
data SrcMeta
= SrcMeta
{ title :: Text,
date :: Text,
tags :: [Text]
}
deriving (Show, Eq, Generic)
instance FromJSON SrcMeta where
parseJSON (Aeson.Object v) = do
title <- v Aeson..: "title"
date <- v Aeson..: "date"
tags <- T.splitOn ";" $ v Aeson..: "keywords"
return SrcMeta { title = title, date = date, tags = tags }
类型不匹配是T.splitOn
需要一个Text
,而.:
returns需要一个Parser
。我在想这个错误吗?将分号分隔的字符串解析为 [Text]
的最佳方法是什么?
您可以先检索 Text
然后拆分它,例如:
instance FromJSON SrcMeta where
parseJSON (Aeson.Object v) = do
title <- v Aeson..: "title"
date <- v Aeson..: "date"
<strong>tags <- v Aeson..: "keywords"</strong>
return SrcMeta { title = title, date = date, tags = <strong>T.splitOn ";" tags</strong> }
另一个选项是使用函子映射 (<$>) :: Functor f => (a -> b) -> f a -> f b
:
instance FromJSON SrcMeta where
parseJSON (Aeson.Object v) = do
title <- v Aeson..: "title"
date <- v Aeson..: "date"
tags <- <strong>T.splitOn ";" <$></strong> (v Aeson..: "keywords")
return SrcMeta { title = title, date = date, tags = tags }