Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This seems to be a known issue with Generics-based parsing. <a href="http://hackage.haskell.org/package/aeson" rel="noreferrer">Aeson</a> has had the same issue and the maintainers have decided to deprecate that functionality in favor of a Template Haskell-based strategy: <a href="https://github.com/bos/aeson/issues/118" rel="noreferrer">https://github.com/bos/aeson/issues/118</a></p> <p>With Aeson, your code would look very similar:</p> <pre><code>import Data.Aeson import Data.Aeson.TH data Record = Record { myMandatoryField :: Integer, myOptionalField :: Maybe Integer } deriving (Eq, Show) $(deriveJSON id ''Record) </code></pre> <p>This way, the <code>Maybe</code> field encodes and decodes as expected:</p> <pre><code>$ ghci λ :l Main.hs Ok, modules loaded: Main. λ encode $ Record 5 Nothing "{\"myOptionalField\":null,\"myMandatoryField\":5}" λ decode it :: Maybe Record Just (Record {myMandatoryField = 5, myOptionalField = Nothing}) </code></pre> <p><strong>UPDATE</strong>: As mentioned in the comments, null-field omission is available with Template Haskell in Aeson HEAD, but that's not yet on Hackage. You can get that behavior today with hand-written <code>FromJSON</code>/<code>ToJSON</code> instances:</p> <pre><code>instance FromJSON Record where parseJSON = withObject "record" $ \o -&gt; Record &lt;$&gt; o .: "myMandatoryField" &lt;*&gt; o .:? "myOptionalField" instance ToJSON Record where toJSON (Record manf optf) = object $ catMaybes [ ("myMandatoryField" .=) &lt;$&gt; pure manf , ("myOptionalField" .=) &lt;$&gt; optf ] </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload