Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I get out of a type? JSON Parsing with Data.Aeson
    text
    copied!<p>Haskell beginner here. I want to pass a "type" parameter with JSON, and have it parse into a native Haskell type using read. The following works: </p> <pre><code>data CreatureType = Bot | Player deriving (Generic, Typeable, Show, Read) data Creature = Creature CreatureType deriving (Typeable, Show) instance FromJSON Creature where parseJSON (A.Object v) = Creature &lt;$&gt; read &lt;$&gt; (v .: "type") parseJSON _ = mzero </code></pre> <p>I want to change it to work with <code>readMay</code>, so that it doesn't crash if read fails. I keep getting stuck. parseJSON needs to return <code>mzero</code> if <code>readMay</code> returns <code>Nothing</code>. </p> <p>Main Question: How can I get this function to use <code>readMay</code> to return <code>mzero</code> on a failure with read?</p> <p>Here's what I've tried: </p> <pre><code>instance FromJSON Creature where parseJSON (A.Object v) = do let t = (v .: "type") :: Parser String mt = readMay &lt;$&gt; t :: Parser (Maybe CreatureType) -- ?? -- guard -- I can't use this because it wants a Bool, and I only have Parser Bool -- Creature &lt;$&gt; read &lt;$&gt; mt parseJSON _ = mzero </code></pre> <p><code>mt</code> is <code>Parser (Maybe CreatureType)</code>. How can I change what I return if it is <code>Nothing</code>? I can't use pattern matching, because <code>Data.Aeson</code> doesn't seem to export a value constructor for Parser. I can't seem to find any methods that will give me the value inside a parser, so, is there a generic haskell method that does it? I've looked at <code>Control.Applicative</code> and can't find anything. Here are the docs for <code>Data.Aeson</code>. <a href="http://hackage.haskell.org/packages/archive/aeson/0.5.0.0/doc/html/Data-Aeson.html" rel="nofollow">http://hackage.haskell.org/packages/archive/aeson/0.5.0.0/doc/html/Data-Aeson.html</a></p>
 

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