haskell / haskell/aeson

Default value on null, undefined or wrong type.

Open
#870 3 comments 0 reactions 0 assignees View on GitHub
Dominant language
Haskell
Stars
1.3k
Forks
336
Avg merge
3d 7h
Merged PRs (30d)
4

Description

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:
```haskell
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:
```haskell
(.|>) :: 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:
```haskell
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 ?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.