[英]How can I manipulate an Aeson value?
I'm trying to parse some blog posts that have tag metadata as semicolon-separated strings, eg:我正在尝试解析一些将标签元数据作为分号分隔的字符串的博客文章,例如:
#+title: Some Title
#+date: 2021-02-04
#+keywords: tag1; tag two; tag three
I have a data structure for them, and I just need to get the Aeson parser to split on semicolons.我有他们的数据结构,我只需要让 Aeson 解析器按分号拆分。 However, it seems it's not as simple as this:
然而,它似乎并不像这样简单:
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 }
The type mismatch is that T.splitOn
needs a Text
, and .:
returns a Parser
.类型不匹配是
T.splitOn
需要一个Text
,并且.:
返回一个Parser
。 Am I thinking about this wrong?我想错了吗? What's the best way of parsing a semicolon-separated string into a
[Text]
?将分号分隔的字符串解析为
[Text]
的最佳方法是什么?
You can first retrieve the Text
and then split it, like:您可以先检索
Text
,然后将其拆分,例如:
instance FromJSON SrcMeta where
parseJSON (Aeson.Object v) = do
title <- v Aeson..: "title"
date <- v Aeson..: "date"
tags <- v Aeson..: "keywords"
return SrcMeta { title = title, date = date, tags = T.splitOn ";" tags }
another option is working with a functor mapping (<$>):: Functor f => (a -> b) -> fa -> fb
:另一种选择是使用仿函数映射
(<$>):: Functor f => (a -> b) -> fa -> fb
:
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 }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.