Reputation: 173
Trying out Edward Kmett's mind expanding lens and lens-aeson package. Here's a warmup
s = "{ \"somekey\" : [ { \"deeperkey\" : 1} , {\"deeperkey\": 2, \"otherkey\":3}]}
The desired result is
[(1, Nothing), (2, Just 3)]
I can make a little progress with
import Control.Lens.Aeson
import Control.Lens
import Control.Monad
import qualified Data.Vector as V
λ> s ^. key "somekey" . _Array . to V.toList >>= (^.. key "deeperkey" . _Number)
[1,2]
But I so far haven't figure out how to work the combinators hard enough to get the correct answer. I most probably involves the fragment ' key "otherkey" '. Any ideas?
Upvotes: 4
Views: 1305
Reputation: 74344
Try this
s ^.. key "somekey" . _Array . traverse
. to (\o -> ( o ^?! key "deeperkey" . _Number
, o ^? key "otherkey" . _Number
)
)
With (^..)
to get multiple elements from the traverse
Traversal
and Array
to match on the multiple values in the "somekey"
slot. Technically the key "deeperkey"
should be allowed to fail, but based on your return type you're making strong assumptions that it doesn't---so we use (^?!)
to do the failing (^?)
without a Maybe
monad for protection.
Upvotes: 3