4

只需阅读精彩的“ 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"]

我错过了棱镜的全部意义吗?或者这是一个合法的用例?

干杯!

4

1 回答 1

7

您想nth 0valueswhich 替换 Aeson 数组的遍历。

此外,由于您有一个具有多个结果的遍历并且想要一个列表而不是 Maybe,因此您必须使用^..而不是^?.

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

正如 Carl 有用地指出的那样,您可以. _String在末尾添加 a 以直接取出字符串:

*Main> locations ^.. key "Locations" . values . key "averageReview" . nth 0 . _String
["5","4","3","2","1"]
于 2014-06-10T23:04:53.963 回答