Skip to content

Commit 088d762

Browse files
committed
Lossless Maybe encoding/decoding
Fixes #22, in a backwards-compatible way.
1 parent e1f9d49 commit 088d762

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

src/Data/Argonaut/Decode/Class.purs

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,9 +68,18 @@ gDecodeJson' signature json = case signature of
6868
mFail msg = maybe (Left msg) Right
6969

7070
instance decodeJsonMaybe :: DecodeJson a => DecodeJson (Maybe a) where
71-
decodeJson j
72-
| isNull j = pure Nothing
73-
| otherwise = Just <$> decodeJson j
71+
decodeJson j =
72+
case decode j of
73+
Right x -> Right x
74+
Left x -> backwardsCompat
75+
where
76+
decode =
77+
decodeJObject >=> lookupJust >=> decodeJson
78+
lookupJust =
79+
maybe (Left "Missing property 'just'") Right <<< SM.lookup "just"
80+
backwardsCompat
81+
| isNull j = pure Nothing
82+
| otherwise = Just <$> decodeJson j
7483

7584
instance decodeJsonTuple :: (DecodeJson a, DecodeJson b) => DecodeJson (Tuple a b) where
7685
decodeJson j = decodeJson j >>= f

src/Data/Argonaut/Encode/Class.purs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ module Data.Argonaut.Encode.Class where
22

33
import Prelude
44

5-
import Data.Argonaut.Core (Json(), jsonNull, fromBoolean, fromNumber, fromString, fromArray, fromObject)
5+
import Data.Argonaut.Core (Json(), jsonNull, fromBoolean, fromNumber, fromString, fromArray, fromObject, jsonEmptyObject, jsonSingletonObject)
66
import Data.Either (Either(), either)
77
import Data.Foldable (foldr)
88
import Data.Generic (class Generic, GenericSpine(..), toSpine)
@@ -42,8 +42,8 @@ gEncodeJson' = case _ of
4242
SM.insert field.recLabel (gEncodeJson' $ field.recValue unit)
4343

4444
instance encodeJsonMaybe :: EncodeJson a => EncodeJson (Maybe a) where
45-
encodeJson Nothing = jsonNull
46-
encodeJson (Just a) = encodeJson a
45+
encodeJson Nothing = jsonEmptyObject
46+
encodeJson (Just a) = jsonSingletonObject "just" (encodeJson a)
4747

4848
instance encodeJsonTuple :: (EncodeJson a, EncodeJson b) => EncodeJson (Tuple a b) where
4949
encodeJson (Tuple a b) = encodeJson [encodeJson a, encodeJson b]

0 commit comments

Comments
 (0)