title: Decode record while mapping a specific field
body: <p>I have a record that looks like this:</p>
  
  <pre><code>data List a = List
      { list_count     :: Int
      , list__embedded :: [a]
      -- ^The actual data you’re looking for.
      }
      deriving (Show)
  </code></pre>
  
  <p>The <code>list__embedded</code> field is from an external API, where the embeds are actually an object:</p>
  
  <pre><code>{
    "count": 5,
    "_embedded": {
      "payments": [
          // payment records that derive FromJSON
      ]
    }
  }
  </code></pre>
  
  <p>As you can see, the <code>_embedded</code> field is actually an object, but I'm only interested in the value of it.</p>
  
  <p>I tried to solve it by writing the <code>FromJSON</code> implementation as following:</p>
  
  <pre><code>instance Aeson.FromJSON a =&gt; Aeson.FromJSON (List a) where
      parseJSON (Aeson.Object v) = List
          &lt;$&gt; Aeson.parseField v "count"
          &lt;*&gt; fmap HashMap.elems (Aeson.parseField v "_embedded")
      parseJSON invalid = Aeson.typeMismatch "Not a correct embed for a list" invalid
  </code></pre>
  
  <p>But I keep running into a type mismatch:</p>
  
  <pre><code>• Could not deduce (Aeson.FromJSONKey k0)
      arising from a use of ‘Aeson.parseField’
    from the context: Aeson.FromJSON a
      bound by the instance declaration
      at src/Mollie/API/Types.hs:366:10-52
    The type variable ‘k0’ is ambiguous
    These potential instances exist:
      instance Aeson.FromJSONKey Integer
        -- Defined in ‘aeson-1.2.4.0:Data.Aeson.Types.FromJSON’
      instance Aeson.FromJSONKey Text.Text
        -- Defined in ‘aeson-1.2.4.0:Data.Aeson.Types.FromJSON’
      instance Aeson.FromJSONKey Time.Day
        -- Defined in ‘aeson-1.2.4.0:Data.Aeson.Types.FromJSON’
      ...plus 14 others
      ...plus 14 instances involving out-of-scope types
      (use -fprint-potential-instances to see them all)
  • In the second argument of ‘fmap’, namely
      ‘(Aeson.parseField v "_embedded")’
    In the second argument of ‘(&lt;*&gt;)’, namely
      ‘fmap HashMap.elems (Aeson.parseField v "_embedded")’
    In the first argument of ‘(&lt;*&gt;)’, namely
      ‘List &lt;$&gt; Aeson.parseField v "count"
         &lt;*&gt; fmap HashMap.elems (Aeson.parseField v "_embedded")’
      |
  369 |         &lt;*&gt; fmap HashMap.elems (Aeson.parseField v "_embedded")
      |                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  </code></pre>
  
  <p>I not quite sure how to make this work.</p>