aeson
aeson copied to clipboard
Add `withTypeableObject` that extracts name of the object from the type
Usually when I have custom data type like this one:
data Foo = Foo
{ fooBar :: Int
, fooBaz :: Double
}
I write FromJSON instance like this:
instance FromJSON Foo where
parseJSON = withObject "Foo" $ \o -> ...
I need to specify name of the type to get good error messages. But if type name changes, I need to not forget to update this function. Also, it's not really convenient to write name of type each type. I propose to add the following function to the aeson library:
typeName :: forall a . Typeable a => Text
typeName = show $ typeRep $ Proxy @a
withTypeableObject :: forall a . Typeable a => (Object -> Parser a) -> Value -> Parser a
withTypeableObject = withObject (typeName @a)