Add FromJSON/ToJSON type classes for converting between custom data types and JValues
When working on projects that depend on the json
package, I frequently find myself defining a pair of type classes for converting between JValue
s and custom types:
class FromJSON a where
-- | Converts from a JSON value to the type.
fromJSON :: JValue -> Either String a
-- | Converts from a JSON value to the list type.
-- Useful for providing a separate overload for strings and other arrays,
-- similar to showList and show.
listFromJSON :: JValue -> Either String [a]
listFromJSON j = case j of
JArray vs -> mapM fromJSON vs
_ -> Left $ "Expected array but was: " ++ ppJSON j
class ToJSON a where
-- | Converts from the type to JSON.
toJSON :: a -> JValue
-- | Converts from the list type to JSON.
listToJSON :: [a] -> JValue
listToJSON = JArray . (toJSON <$>)
-- | Generates a JSON string from a value of type.
toJSONString :: a -> String
toJSONString = ppJSON . toJSON
(see here)
By implementing these type classes for custom types, especially complex structures, serializing and deserializing data to and from JSON becomes a lot more convenient. While it is of course easy to define these classes downstream, especially libraries could probably benefit from standardized conversion classes.
This approach is inspired by aeson
's FromJSON
/ToJSON
classes in Haskell.
Edited by Fredrik Wieczerkowski