Aeson Prism带有“免费”参考

时间:2014-06-10 22:33:25

标签: haskell lens aeson

阅读精彩的" Lens/Aeson Traversals/Prisms"文章并拥有真实的应用程序。鉴于以下匿名JSON结构,我如何棱析出集合而不是特定值?

{"Locations" : [ {"id" : "2o8434", "averageReview": ["5", "1"]},{"id" : "2o8435", "averageReview": ["4", "1"]},{"id" : "2o8436", "averageReview": ["3", "1"]},{"id" : "2o8437", "averageReview": ["2", "1"]},{"id" : "2o8438", "averageReview": ["1", "1"]}]}

我有:

λ> locations ^? key "Locations" . nth 0 . key "averageReview" . nth 0
Just (String "5")

我想要的是什么:

λ> locations ^? key "Locations" . * . key "averageReview" . nth 0
["5", "4", "3", "2", "1"]

我是否错过了整个棱镜点?或者这是一个合法的用例吗?

干杯!

1 个答案:

答案 0 :(得分:6)

您希望将nth 0替换为values,这是对Aeson数组的遍历。

此外,由于您的遍历包含多个结果,并且需要列表而不是“可能”,因此您必须使用^..而不是^?

*Main> locations ^.. key "Locations" . values . key "averageReview" . nth 0
[String "5",String "4",String "3",String "2",String "1"]

正如卡尔有用地指出的那样,你可以在末尾添加一个. _String来直接输出字符串:

*Main> locations ^.. key "Locations" . values . key "averageReview" . nth 0 . _String
["5","4","3","2","1"]