问题描述
我有一个(有效)json编码的数组,该数组缺少数据或格式错误.我希望Aeson将其转换为Maybe [Maybe Point]
并使用Nothing
,其中数组元素不是有效的Point
.
I have a (valid) json encoded array that has missing or malformed data. I want Aeson to turn that into Maybe [Maybe Point]
and have Nothing
where the array element was not a valid 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无法做到这一点,那么还有另一个图书馆可以做到吗?
If this can't be done with Aeson, is there another library that can do it?
请注意,实际对象比简单的整数复杂得多,因此字符串操作不是可行的解决方案.
Note that the actual object is much more complex than a simple integer so string manipulations are not a viable solution.
推荐答案
我会使用Values并从中使用它们:
I would use Values and work from them:
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]
一个非常无效(但安全)的解决方案是:
A very ineffective (but safe) solution would be:
> 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]
如果您想使事情更有效,则可能需要使用Vector
s和foldl'
.
If you want to make things more effective you might want to use Vector
s and foldl'
.
这篇关于Haskell Aeson处理丢失的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!