我有一个(有效)json编码的数组,该数组缺少数据或格式错误。我希望Aeson将其转换为Maybe [Maybe Point]并具有Nothing,其中数组元素不是有效的Point

import Data.Aeson
decode "[1,2,3,4,null,\"hello\"]" :: (Maybe [Maybe Int])
=> Nothing


但是我宁愿让它评估为

=> Just [Just 1, Just 2, Just 3, Just 4, Nothing, Nothing]


如果使用Aeson无法做到这一点,那么还有另一个库可以做到吗?

请注意,实际对象比简单的整数复杂得多,因此字符串操作不是可行的解决方案。

最佳答案

我将使用Values并从中进行工作:

decode "[1,2,3,4,null,\"hello\"]" :: (Maybe [Value])
Just [Number 1.0,Number 2.0,Number 3.0,Number 4.0,Null,String "hello"]


所以

> let fromNum v = case v of Number x -> Just x ; _ -> Nothing
> maybe [] (map fromNum) (decode  "[1,2,3,4,null,\"hello\"]" :: (Maybe [Value])
[Just 1.0,Just 2.0,Just 3.0,Just 4.0,Nothing,Nothing]


一个非常无效(但安全)的解决方案是:

> let tmp = maybe [] (map fromNum) (decode  "[1,2,3,4,null,\"hello\"]" :: (Maybe [Value])
> let keepJust l v = case v of Just i -> i:l; Nothing -> l
> reverse (foldl keepJust [] tmp)
[1.0,2.0,3.0,4.0]


如果您想使事情更有效,则可能需要使用Vectorfoldl'

关于haskell - Haskell Aeson处理丢失的数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33912046/

10-11 08:56