如何浏览大型Aeson
Values
?我知道应该有一个我感兴趣的字符串嵌套在结构中的某个地方。我怎么能找到它?
到目前为止,我只知道如何查询构造函数并发现它是一个数组。我怎样才能深入挖掘?
> take 20 $ show bt
"Array (fromList [Obj"
答案 0 :(得分:4)
lens
包具有检查像JSON Value
这样的树状结构的有用功能。还有lens-aeson
包,其中包含额外的JSON特定功能。
import Data.Text
import Data.Aeson
import Data.Aeson.Lens (_Value,_String) -- this is from lens-aeson
import Data.Foldable (toList)
import Control.Lens (Fold,folding,universeOf,toListOf,paraOf,preview)
我们可以从定义镜头Fold
开始,提取给定JSON Values
的直接孩子Value
:
vchildren :: Fold Value Value
vchildren = folding $ \v -> case v of
Object o -> toList o
Array a -> toList a
_ -> []
folding
是来自lens
的函数,它创建一个返回列表的Fold
函数。在我们的例子中,Value
的列表。
我们可以将vchildren
与universeOf
中的Control.Lens.Plated
函数结合使用,以获取一个提取所有 Value
的传递后代的函数,包括自己:
allValues :: Value -> [Value]
allValues = universeOf vchildren
此函数提取Value
中包含的所有文本。它使用来自_String
的Data.Aeson.Lens
棱镜(Prism
有点像可以传递的“具体化”模式):
allTexts :: Value -> [Text]
allTexts = toListOf (folding allValues . _String)
Control.Lens.Plated
也有一些有趣的功能,例如paraOf
,可以让你构建“paramorphims”。一个paramorphism是一个从树叶开始的树状结构的“受控破坏”,并向上建立结果。例如,这个函数
vpara :: (Value -> [r] -> r) -> Value -> r
vpara = paraOf vchildren
将另一个函数作为其第一个参数,该函数接收“当前节点”以及下面节点的中间结果,并为当前节点构建中间结果。
vpara
将开始使用叶子中的JSON值(这些节点的中间结果列表只是[]
)并向上进行。
vpara
的一种可能用途是获取JSON中以与某些条件匹配的文本结尾的路径列表,如下所示:
type Path = [Value]
pathsThatEndInText :: (Text -> Bool) -> Value -> [Path]
pathsThatEndInText pred = vpara func
where
func :: Value -> [[Path]] -> [Path]
func v@(String txt) _ | pred txt = [[v]]
func v l@(_:_) = Prelude.map (v:) (Prelude.concat l)
func _ _ = []
获取pathsThatEndInText
返回的其中一条路径的可读描述:
import qualified Data.HashMap.Strict as HM
import qualified Data.Vector as V
describePath :: Path -> [String]
describePath (v:vs) = Prelude.zipWith step (v:vs) vs
where
step (Object o) next = (unpack . Prelude.head . HM.keys . HM.filter (==next)) o
step (Array a) next = (show . maybe (error "not found") id) (V.elemIndex next a)
step _ _ = error "should not happen"
最后,这是用于在ghci中测试上述函数的示例JSON值:
exampleJSON :: Value
exampleJSON = maybe Null id (preview _Value str)
where
str = "[{ \"k1\" : \"aaa\" },{ \"k2\" : \"ccc\" }, { \"k3\" : \"ddd\" }]"
这是gist。