Skip to content

Commit

Permalink
Add maybeKey combinator (#37)
Browse files Browse the repository at this point in the history
* Add maybeKey combinator

* remove prefixes
  • Loading branch information
avanov committed Sep 3, 2023
1 parent b290cef commit d2abf76
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/Data/Aeson/Combinators/Decode.hs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ module Data.Aeson.Combinators.Decode (
, jsonNull
-- *** Objects
, key
, maybeKey
, at
-- *** Arrays
, index
Expand Down Expand Up @@ -426,6 +427,20 @@ key t (Decoder d) = Decoder $ \case
val -> typeMismatch "Object" val
{-# INLINE key #-}

-- | Same as 'key' but works with omitted attributes in payloads and produces parsed values in the context of 'Maybe'.
-- Note that this combinator behaves differently to a combination of 'maybe' and 'key', which produce error if
-- the attribute is missing from the json object.
-- >>> decode (maybeKey "data" int) "{}"
-- Just Nothing
--
--- >>> decode (maybeKey "data" int) "{\"data\": 42}"
-- Just (Just 42)
maybeKey :: Key -> Decoder a -> Decoder (Maybe a)
maybeKey t (Decoder d) = Decoder $ \case
Object v -> (v .:? t) >>= maybe (pure Nothing) (fmap Just . d)

Check failure on line 440 in lib/Data/Aeson/Combinators/Decode.hs

View workflow job for this annotation

GitHub Actions / stack-aeson-2

• Couldn't match expected type: (Value -> Parser (Maybe a))
val -> typeMismatch "Object" val
{-# INLINE maybeKey #-}


-- | Extract JSON value from JSON object keys
--
Expand Down

0 comments on commit d2abf76

Please sign in to comment.