Skip to content

Lossless Maybe encoding/decoding #23

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 7, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions src/Data/Argonaut/Decode/Class.purs
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,18 @@ gDecodeJson' signature json = case signature of
mFail msg = maybe (Left msg) Right

instance decodeJsonMaybe :: DecodeJson a => DecodeJson (Maybe a) where
decodeJson j
| isNull j = pure Nothing
| otherwise = Just <$> decodeJson j
decodeJson j =
case decode j of
Right x -> Right x
Left x -> backwardsCompat
where
decode =
decodeJObject >=> lookupJust >=> decodeJson
lookupJust =
maybe (Left "Missing property 'just'") Right <<< SM.lookup "just"
backwardsCompat
| isNull j = pure Nothing
| otherwise = Just <$> decodeJson j

instance decodeJsonTuple :: (DecodeJson a, DecodeJson b) => DecodeJson (Tuple a b) where
decodeJson j = decodeJson j >>= f
Expand Down
6 changes: 3 additions & 3 deletions src/Data/Argonaut/Encode/Class.purs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ module Data.Argonaut.Encode.Class where

import Prelude

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

instance encodeJsonMaybe :: EncodeJson a => EncodeJson (Maybe a) where
encodeJson Nothing = jsonNull
encodeJson (Just a) = encodeJson a
encodeJson Nothing = jsonEmptyObject
encodeJson (Just a) = jsonSingletonObject "just" (encodeJson a)

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