title: Parsing nested JSON into a list of Tuples with Aeson
body: <p>Say I have the following structure:</p>
  
  <pre><code>data AddressDto = AddressDto
    { addressDtoId                   :: UUID 
    , addressDtoCode                 :: Text
    , addressDtoCity                 :: Maybe Text 
    , addressDtoStreet               :: Text 
    , addressDtoPostCode             :: Text
    } deriving (Eq, Show, Generic)
  
  instance FromJSON AddressDto where
    parseJSON = genericParseJSON $ apiOptions "addressDto"
  
  instance ToJSON AddressDto where
    toJSON = genericToJSON $ apiOptions "addressDto"
    toEncoding = genericToEncoding $ apiOptions "addressDto"
  </code></pre>
  
  <p>This works as you would expect.</p>
  
  <p>Now say I want to parse a JSON structure of the format:</p>
  
  <pre><code>{ UUID: AddressDto, UUID: AddressDto, UUID: AddressDto }
  </code></pre>
  
  <p>A reasonable Haskell representation would seem to be:</p>
  
  <pre><code>data AddressListDto = AddressListDto [(UUID, AddressDto)]
  </code></pre>
  
  <p>Creating a helper function like so:</p>
  
  <pre><code>keyAndValueToList :: Either ServiceError AddressListDto -&gt; Text -&gt; DiscountDto -&gt; Either ServiceError AddressListDto
  keyAndValueToList (Left err) _ _ = Left err
  keyAndValueToList (Right (AddressListDto ald)) k v = do
    let maybeUUID = fromString $ toS k 
    case maybeUUID of 
      Nothing        -&gt; Left $ ParseError $ InvalidDiscountId k
      Just validUUID -&gt; Right $ AddressListDto $ (validUUID, v) : ald
  </code></pre>
  
  <p>and finally an instance of FromJSON:</p>
  
  <pre><code>instance FromJSON AddressListDto where
    parseJSON = withObject "tuple" $ \o -&gt; do 
      let result = foldlWithKey' keyAndValueToList (Right $ AddressListDto []) o
      case result of
        Right res -&gt; pure res
        Left err -&gt; throwError err
  </code></pre>
  
  <p>This fails to compile with:</p>
  
  <pre><code>Couldn't match type ‘aeson-1.4.5.0:Data.Aeson.Types.Internal.Value’
                       with ‘AddressDto’
        Expected type: unordered-containers-0.2.10.0:Data.HashMap.Base.HashMap
                         Text AddressDto
  </code></pre>
  
  <p>Two questions:</p>
  
  <p>1) How do I make sure the nested values in the hashmap get parsed correctly to an AddressDto.
  2) How do I avoid forcing the initial value into an either? Is there a function I could use instead of <code>foldlWithKey'</code> that didn't make me wrap the initial value like this?</p>