From 00e42a1eeaf17cd0acf46f86cd07f806388e1d6c Mon Sep 17 00:00:00 2001 From: Felix Paulusma Date: Tue, 29 Aug 2017 18:21:17 +0200 Subject: [PATCH] Added getFieldOptional' to Decode.Combinators The regular getFieldOptional doesn't return Nothing when the value of the field is null. getFieldOptional' does give Nothing when the field is null. The operator aliasses are changed to mimic the Haskell Data.Aeson libraries implementation. (If, for legacy reasons, the alias for the old getFieldOptional shouldn't change, then switch (.??) for (.?!) and vice-versa.) --- src/Data/Argonaut/Decode/Combinators.purs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/Data/Argonaut/Decode/Combinators.purs b/src/Data/Argonaut/Decode/Combinators.purs index b549d59..3b6a77c 100644 --- a/src/Data/Argonaut/Decode/Combinators.purs +++ b/src/Data/Argonaut/Decode/Combinators.purs @@ -17,6 +17,7 @@ getField o s = infix 7 getField as .? +-- | Will return Nothing if the field isn't present getFieldOptional :: forall a. DecodeJson a => JObject -> String -> Either String (Maybe a) getFieldOptional o s = maybe @@ -26,7 +27,21 @@ getFieldOptional o s = where decode json = Just <$> decodeJson json -infix 7 getFieldOptional as .?? +infix 7 getFieldOptional as .?! + +-- | Will return Nothing if the field isn't present or the value is null +getFieldOptional' :: forall a. DecodeJson a => JObject -> String -> Either String (Maybe a) +getFieldOptional' o s = + maybe + (pure Nothing) + decodeIt + (SM.lookup s o) + where decodeIt j = + if isNull j + then pure Nothing + else Just <$> decodeJson j + +infix 7 getFieldOptional' as .?? defaultField :: forall a. Either String (Maybe a) -> a -> Either String a defaultField parser default = fromMaybe default <$> parser