aeson icon indicating copy to clipboard operation
aeson copied to clipboard

Default value on null, undefined or wrong type.

Open kamek-pf opened this issue 4 years ago • 3 comments

Hi,

I have several use cases where it makes sense to fall back to a default value when the key you're looking for is either null, missing entirely or of the wrong type.

The following pattern is described in the documentation:

 v1 <- o .:? "optFieldWithDefault" .!= 1.0 -- fails if optFieldWithDefault is set to a boolean for instance

This works fine for null or missing keys, but fails when the key is of the wrong type. I ended up defining my own operator:

(.|>) :: Parser (Maybe a) -> a -> Parser a
(.|>) parser def = parser .!= def <|> pure def

Which is used the exact same way as .!= but also falls back to your desired default value on invalid type:

 v1 <- o .:? "optFieldWithDefault" .|> 1.0 -- will default to 1.0 on null, undefined, or unexpected type

Would it make sense to add such an operator to Aeson, possibly under a different name ?

kamek-pf avatar Sep 21 '21 00:09 kamek-pf

How

 v1 <- o .:? "optFieldWithDefault" .|> 1.0 

is different from

 v1 <- o .: "optFieldWithDefault" <|> pure 1.0

?

phadej avatar Sep 21 '21 10:09 phadej

That's what I did at first, if optFieldWithDefault is null:

v1 evaluates to NaN here:

v1 <- o .: "optFieldWithDefault" <|> pure 1.0

v1 evaluates to 1.0 here:

v1 <- o .:? "optFieldWithDefault" .|> 1.0 

I assume this is because for floating point numbers, the parser evaluates null to NaN, I don't know if there are other cases where this might make sense.

kamek-pf avatar Sep 21 '21 15:09 kamek-pf

IIRC Float, Double and Maybe (Nothing) are the only types which we encode to null, so there aren't many types for which behavior is different, and they are kind of special. I'd suggest using something monomorphic. (E.g. with Float and Double you might want to encode infinities differently - which we will do in the next version, as currently infinities are also encoded to null. I cannot find an issue for that though).

phadej avatar Sep 21 '21 15:09 phadej