purescript-contrib/purescript-argonaut-codecs

Should Maybe codec return `Nothing` for nulls?

garyb opened this issue · 2 comments

If you're writing a codec for a value that cannot have a DecodeJson instance declared for it, it seems sensible to write something like this:

traverse decodeCustom =<< obj .? "prop"

To get a Maybe Custom success result. The idea being obj .? "prop" result is a Maybe Json and then decodeCustom does the Json -> Custom step. However, the decodeJsonJson instance always succeeds, as null is a decodeable value, so you end up with Just null as the response, and then decodeCustom fails as it's probably expecting something else.

If you're using instances everywhere this works fine, as the custom decoder would run "inside" the Maybe decoder, and failing there gives you a Nothing result.

Maybe it was a faulty assumption on my part that null values would be considered Nothing? It took me a really long time to track this down though. 😭

Oh, just to point out, this was found while trying to test a encode/decode roundtrip - Nothing does get encoded as null, so that didn't help my assumption that it would be decoded as such also.

Yeah, I think null -> Nothing, Nothing -> null makes sense.