I have an incoming JSON which looks like:
{
"somekey": [
{ "objectType": "typeA"
, "key1": "val1"
, "key2": "val2"
}
, { "objectType": "typeB"
, "key3": "val3"
, "key4": "val4"
}
]
While parsing, I want to deal with ONLY objects tagged with typeA
. I've got the following code to work, but I'm looking at something more idiomatic that will use the power of lenses properly AND will result in a better error message if the parsing fails:
import Control.Lens
import Data.Aeson.Lens (values, key, _String)
instance FromJSON MyType where
parseJson = Aeson.withObject "Expecting JSON object" $ \o -> do
allItems <- o .: "someKey"
let selectedItems :: [Aeson.Value] = filter (\x -> x ^? (key "objectType") . _String == Just "typeA") $ allItems ^.. values
someKey <- mapM parseJON selectedItems
pure MyType{..}