title: Parsing an Options Object to a List of Options
body: <p>I have been working on a small library against an JSON-based API.  This library makes use of an "options" object, a series of key-value pairs that specify advanced behaviour:</p>
  
  <pre><code>{
    "id": 1234
    ...
    "options": {
      "notify_no_data": True,
      "no_data_timeframe": 20,
      "notify_audit": False,
      "silenced": {"*" :1428937807}
    }
  }
  </code></pre>
  
  <p>I've represented the options concept in Haskell using a list of options:</p>
  
  <pre><code>data Option = NotifyNoData NominalDiffTime -- notify after xyz
              | NotifyAudit -- notify on changes
              | Silenced (Maybe UTCTime) -- silence all notifications ("*") until xyz (or indefinitely)
  
  newtype Options = Options [Option]
  </code></pre>
  
  <p>Implementing <code>toJSON</code> was simple enough; I instantiated <code>toJSON</code> for the <code>Option</code> type, and then used those as helpers for the <code>Options</code> type.</p>
  
  <pre><code>instance ToJSON Option where
    toJSON (Silenced mtime) =
      Object $ Data.HashMap.fromList [("silenced", mapping)]
      where stamp = maybe Null (jsonTime . floor . utcTimeToPOSIXSeconds) mtime
            mapping = Object $ Data.HashMap.singleton "*" stamp
    toJSON (NotifyNoData difftime) =
      Object $ Data.HashMap.fromList [("notify_no_data", Bool True)
                                     ,("no_data_timeframe", stamp)]
      where stamp = jsonTime $ floor (difftime / 60)
    toJSON NotifyAudit =
      Object $ Data.HashMap.fromList [("notify_audit", Bool True)]
  
  instance ToJSON Options where
    toJSON (Options options) = Object $ Data.HashMap.unions $ reverse $ (opts:) $ map ((\(Object o) -&gt; o) . toJSON) options
      where opts = Data.HashMap.fromList [("silenced", Object Data.HashMap.empty)
                                         ,("notify_no_data", Bool False)
                                         ,("notify_audit", Bool False)]
  </code></pre>
  
  <p>The problem I am running into is in the <code>fromJSON</code> implementation for <code>Options</code>.  All the use cases I've seen before supply a fairly simple json-object-representation to data-representation mapping.  What I need to do is convert an object to an object of options to a list of data (Option) representations.  For example, the sample JSON under "options" that I gave at the start would have to become:</p>
  
  <pre><code>Options [NotifyNoData 20, Silenced (Just (posixSecondsToUTCTime 1428937807))]
  </code></pre>
  
  <p><code>FromJSON</code> requires an implementation of <code>parseJSON :: FromJSON a =&gt; Value -&gt; Parser a</code>.  I am having trouble understanding how to build a Parser using this optional object structure given by the API.  Is there a standard approach to parsing a JSON object to a list like this?  It may be that I am failing to fully understand the <code>Parser</code> typeclass.</p>