Add JSON Path context to a parser
When parsing a complex structure, it helps to annotate (sub)parsers with context, so that if an error occurs, you can find its location.
withObject "Person" $ \o ->
Person
<$> o .: "name" <?> Key "name"
<*> o .: "age" <?> Key "age"
(Standard methods like '(.:)' already do this.)
The description is actually optional, requiring .: forces the key
to be present in the JSON file (possibly null). Using .:? removes
this limitation.
aeson
documentation says the following about<?>
:Add JSON Path context to a parser When parsing a complex structure, it helps to annotate (sub)parsers with context, so that if an error occurs, you can find its location.
withObject "Person" $ \o -> Person <$> o .: "name" <?> Key "name" <*> o .: "age" <?> Key "age"
(Standard methods like '(.:)' already do this.)
The description is actually optional, requiring
.:
forces the key to be present in the JSON file (possiblynull
). Using.:?
removes this limitation.