title: Is it possible to match a changing JSON key to a sum type data constructor with aeson inside a larger record type?
body: <p>So I have this data type <code>ItemType</code> which is decoded using its data constructor name (see the FromJSON instance).</p>
  <pre class="lang-hs prettyprint-override"><code>import           Data.Aeson
  import           Data.Aeson.Types
  import           Data.Char (toLower)
  import           GHC.Generics
  
  data ItemType =
      MkLogin Login
    | MkCard Card
    | MkIdentity Identity
    | MkSecureNote Note
    deriving (Generic, Show)
  
  lowercase :: String -&gt; String
  lowercase &quot;&quot; = &quot;&quot;
  lowercase (s:ss) = toLower s : ss
  
  stripPrefix :: String -&gt; String
  stripPrefix ('M':'k':ss) = ss
  stripPrefix str = str
  
  -- | Decode value using ItemType data constructor names
  instance FromJSON ItemType where
    parseJSON = genericParseJSON defaultOptions
      { constructorTagModifier = lowercase . stripPrefix
      , sumEncoding = ObjectWithSingleField }
  </code></pre>
  <p>and what I want to do is add this type as a field to a larger record type called <code>Item</code></p>
  <pre class="lang-hs prettyprint-override"><code>data Item =
    Item { _object :: String
         , _id :: String
         , _organizationId :: Maybe Int
         , _folderId :: Maybe Int
         , _type :: Int
         , _name :: String
         , _notes :: String
         , _favorite :: Bool
         , ??? :: ItemType -- don't know how to add this without a different field name
         , _collectionIds :: [Int]
         , _revisionDate :: Maybe String
         } deriving (Generic, Show)
  
  instance FromJSON Item where
    parseJSON =
      genericParseJSON defaultOptions { fieldLabelModifier = stripUnderscore }
  
  </code></pre>
  <p>However I don't want to create a new field name for the type. Instead I want to use the data constructor which aeson matched on <code>ItemType</code> as the field name because the key of the <code>ItemType</code> field in the JSON object I'm trying to model changes depending upon what <code>ItemType</code> it is. So in this case the key is either &quot;login&quot;, &quot;card&quot;, &quot;identity&quot;, &quot;secureNote&quot;. Perhaps I should be using <code>TaggedObject</code> for the <code>sumEncoding</code>, but I'm not totally sure how it works.</p>
  <p>Example JSON list of <code>Item</code> objects: <a href="https://i.imgur.com/xzHy9MU.png" rel="nofollow noreferrer">https://i.imgur.com/xzHy9MU.png</a>. Here you can see the <code>ItemType</code> field by the keys &quot;login&quot;, &quot;card&quot;, &quot;identity&quot; depending on what type they are.</p>