mniip answer JSON Object Map, , . , , , . , Object HashMap Text Value, HashMap .
, id ident, Haskell , id Prelude Control.Category.
module Aes where
import Control.Applicative
import Data.Aeson
import Data.Text (Text)
import qualified Data.HashMap.Strict as HMS
data PersonInfo = PersonInfo { infoName :: Text, infoAge :: Int }
instance FromJSON PersonInfo where
-- Use mniip definition here
data Person = Person { ident :: Text, name :: Text, age :: Int }
newtype PersonList = PersonList [Person]
instance FromJSON PersonList where
parseJSON (Object v) = PersonList <$> HMS.foldrWithKey go (pure []) v
where
go i x r = (\(PersonInfo nm ag) rest -> Person i nm ag : rest) <$>
parseJSON x <*> r
parseJSON _ = empty
Note that, like the Alexander VoidEx Ruchkin answer , this will consistently convert from PersonInfoto Personexplicitly into a monad Parser. Therefore, it would be easy to modify it to create a parsing error if it Persondoes not perform some high-level validation. Alexander's answer also demonstrates the usefulness of the combinator withObject, which I would use if I knew it existed.
source
share